<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Sean's Ramblings]]></title><description><![CDATA[I write about software, systems, comics, games, and Fhqwhgads. Sometimes that means a technical deep dive; sometimes it's just a tangent]]></description><link>https://rambling.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6aefcf97a529a56101dcc7c8/b4b48c1c-7d10-4720-904a-be3f92cced5f.png</url><title>Sean&apos;s Ramblings</title><link>https://rambling.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 11:16:16 GMT</lastBuildDate><atom:link href="https://rambling.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Command & Conquer: Rivals API]]></title><description><![CDATA[Disclaimer: You should thoroughly read EA’s Command & Conquer: Rivals EULA before engaging in any of the subsequent forensic activity. This is purely for…]]></description><link>https://rambling.hashnode.dev/command-conquer-rivals-api-2f5985167d82</link><guid isPermaLink="true">https://rambling.hashnode.dev/command-conquer-rivals-api-2f5985167d82</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 25 Oct 2026 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/4d013f76-fccb-4c89-a8cc-302c99b269cd.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Disclaimer: You should thoroughly read EA’s</em> <a href="https://www.ea.com/games/command-and-conquer/command-and-conquer-rivals"><em>Command &amp; Conquer: Rivals EULA</em></a> <em>before engaging in any of the subsequent forensic activity. This is purely for educational purposes. And you likely shouldn’t go poking at EA’s production services with your own account</em></p>
<h3>Summary</h3>
<p>I was cleaning up some old files and came across a data dump I took from Rivals. Surprisingly, I also had a draft article to walk through the reverse-engineering process I used to document their API 😅 This post is an attempt to finish what was started and reduce my draft backlog!</p>
<p>It’s worth noting that the captures are from May 2020 (Pixel 3, Android 10, game version 1.8), and the .apk I revisited is version 1.14.0. Endpoints have almost certainly drifted since then, so treat this as a snapshot of what I found, not a living map</p>
<p>The short version: in 2020 I peeked at the .apk, got nowhere useful, and spent my time on mitmproxy captures instead. In 2026 started playing again and went back to the binary, recovered the game server’s protobuf schemas from it, and suddenly those old captures made a lot more sense</p>
<p>That’s the spine of this post and a similar theme if you’ve read these:</p>
<ul>
<li><a href="https://medium.com/sean3z/debugging-mobile-apps-with-mitmproxy-4596e56b3da2">Debugging Mobile Apps with mitmproxy</a></li>
<li><a href="https://medium.com/sean3z/my-c-c-projects-throughout-the-years-23f429ef3d56">My C&amp;C Projects throughout the years</a></li>
</ul>
<h3>Why?</h3>
<p>I thoroughly enjoy Rivals, a free mobile game published by EA, however I would really prefer better statistics than what’s available in-game</p>
<p>For example, understanding how my deck performs against certain players or where I can improve. That itch is what started the 2020 dump, and it’s what finally got me to finish this</p>
<h3>2020: a dead-end .apk and a useful wire dump</h3>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/8d68a7fc-b989-4b36-84aa-003c2b32dfe1.png" alt="" style="display:block;margin:0 auto" />

<p>Back then I opened the .apk (<code>com.ea.gp.candcwarzones</code>) in Android Studio and learned a few things that felt interesting at the time</p>
<ul>
<li>Rivals uses Celdum-Bold and DaytonaPro fonts</li>
<li>EA uses custom <code>.sb</code> / <code>.sba</code> / <code>.sb3d</code> files for assets (animations, models, etc.). There've been a few attempts to crack those, but I wasn't able to find anything readily accessible</li>
<li>The game pulled in Firebase, and I guessed it might be for real-time in-match data transfer (although I never confirmed that)</li>
</ul>
<p>Honestly, the .apk was a bit of a dead end for what I actually wanted. The Java side looked like a shell of SDKs, and the interesting stuff was all on the wire. So I pointed my phone at a mitmproxy instance on my local network (same setup as my mitmproxy post) and just played the game while watching traffic roll by</p>
<p>I’ve always wondered why that worked so easily on Android 10, since apps stopped trusting user-installed certificates back in Android 7. Years later the answer turned out to be sitting in the binary:</p>
<p><code>com.ea.ironmonkey.HTTPRequest</code>, the Java class the native engine uses for HTTP, installs a trust manager that accepts any certificate (it only checks the expiry date) along with an allow-all hostname verifier. Its user agent is <code>"osiris " + http.agent</code>, which is exactly the <code>osiris Dalvik/2.1.0 ...</code> header from my captures. That's the code path the game server calls were going through, and that's why mitmproxy just worked</p>
<p>So, let’s move on to what the wire actually showed</p>
<h3>Rivals API</h3>
<p>Yes, Rivals has an internal (undocumented) API. Saying it’s inconsistent is an understatement (seemingly due to also leveraging EA’s game-agnostic endpoints as well). Some services speak plain JSON, and the game server itself speaks protobuf</p>
<h3>Domains</h3>
<p>Here’s every host I saw the client talk to in 2020, with what I know about each one now</p>
<ul>
<li><code>accounts.ea.com</code> — OAuth, token refresh and token info</li>
<li><code>gateway.ea.com</code> — Identity, personas and persona links</li>
<li><code>friends.gs.ea.com</code> — Friends list and friend invitations</li>
<li><code>groups.gameservices.ea.com</code> — Alliances (EA calls them groups)</li>
<li><code>prod.scorpion-ea.com</code> — The Rivals game server itself (protobuf)</li>
<li><code>prod.us-east-1.battle-service.scorpion-ea.com</code> — Battle service, US region</li>
<li><code>prod.eu-central-1.battle-service.scorpion-ea.com</code> — Battle service, EU region</li>
<li><code>rtm.tnt-ea.com</code> — Real-time messaging (chat and presence)</li>
<li><code>pin-em.data.ea.com</code> — In-game inbox / engagement messages</li>
<li><code>pin-river.data.ea.com</code> — Telemetry (EA's PIN event pipeline, <code>/pinEvents</code>)</li>
<li><code>pn.tnt-ea.com</code> — Push notification registration (EA's PushTNG)</li>
<li><code>ping1.tnt-ea.com</code> — A bare <code>HEAD /</code>, the SDK's "am I online?" check</li>
<li><code>product.sn.eamobile.com</code> — The real-money store catalog</li>
</ul>
<p>A few interesting tidbits from the DNS side. <code>groups.gameservices.ea.com</code> CNAMEs through <code>groupt.tnt-ea.com</code> to an Elastic Beanstalk environment in us-east-1, and <code>rtm.tnt-ea.com</code> lands on an AWS load balancer. So, it's AWS all the way down</p>
<p>Internally the game seems to be codenamed Scorpion (hence <code>scorpion-ea.com</code>), and EA's social stack is Antelope. The persona namespace for Rivals is <code>antelope-scorpion-candcwarzones</code>, which ties both names together</p>
<p>You won’t find most of those hostnames hardcoded, and that’s on purpose. On launch, Nimble calls EA’s “Synergy Director” (<code>https://syn-dir.sn.eamobile.com/director/api/android/getDirectionByPackage</code>) with the package name and some device info. The director replies with a map of service keys to URLs. Here's how the keys line up with the hosts above</p>
<ul>
<li><code>nexus.connect</code>, <code>nexus.proxy</code>, <code>nexus.portal</code>: the identity stack (accounts and gateway)</li>
<li><code>antelope.friends.url</code>, <code>antelope.groups.url</code>, <code>antelope.rtm.host</code>: friends, groups and real-time messaging</li>
<li><code>river.pin</code> and <code>pin.aruba.url</code>: telemetry (<code>/pinEvents</code>) and the inbox (<code>/action</code>)</li>
<li><code>ens.url</code>: push notifications. Nimble's PushTNG module registers the phone's Firebase token at <code>{ens.url}/games/{game}/devices</code>, which is how <code>pn.tnt-ea.com</code> shows up</li>
<li><code>synergy.product</code>: <code>/product/api/core/getAvailableItems</code>, <code>getMTXGameCategories</code> and <code>getDownloadItemUrl</code>, so that's the catalog of real-money purchases behind <code>product.sn.eamobile.com</code></li>
</ul>
<p><code>ping1.tnt-ea.com</code> is hardcoded as <code>MAIN_NETWORK_REACHABILITY_CHECK_URL</code> in Nimble, so it's a connectivity check rather than a latency check. The Scorpion codename is everywhere too: the main activity is <code>ScorpionActivity</code>, and the C++ classes are <code>ScorpionWorld</code>, <code>ScorpionNetworkManager</code> and <code>ScorpionGroupManager</code></p>
<p>I’ve broken up the rest of the API into the following services</p>
<ul>
<li>Authentication</li>
<li>Persona</li>
<li>Friends</li>
<li>Alliance</li>
<li>Game server (protobuf)</li>
<li>Inbox</li>
</ul>
<h3>Authentication</h3>
<p>Rivals uses EA’s standard OAuth flow on <a href="http://accounts.ea.com">accounts.ea.com</a>. The client holds onto a refresh token and trades it for a fresh access token, which only lives for about an hour</p>
<pre><code class="language-plaintext">POST https://accounts.ea.com/connect/token?client_id=candcwarzone-2016-android-client&amp;client_secret=&lt;client_secret&gt;&amp;grant_type=refresh_token&amp;refresh_token=&lt;refresh_token&gt;&amp;release_type=prod
Accept: */*
X-Include-RT-Time: true
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
</code></pre>
<p>Yup, everything rides in the query string, client secret included (with an empty body). Not exactly what you’d expect from an OAuth token endpoint, but here we are</p>
<pre><code class="language-javascript">{
    "access_token": "&lt;access_token&gt;",
    "expires_in": 3599,
    "id_token": "&lt;id_token&gt;",
    "refresh_token": "&lt;refresh_token&gt;",
    "refresh_token_expires_in": 86399,
    "token_type": "Bearer"
}
</code></pre>
<p>So, roughly an hour for the access token and a day for the refresh token. Each refresh hands back a new refresh token, so the client keeps rolling it forward</p>
<p>The Java half of Nimble actually has the exact same string as a form-body template (<code>grant_type=refresh_token&amp;refresh_token=%s&amp;client_id=%s&amp;client_secret=%s&amp;redirect_uri=nucleus:rest</code>), so it was clearly designed as a body. The copy that actually runs in Rivals is the C++ port inside <code>libapp.so</code>, and that's the one sending it in the query string. The other fun bit is that neither the client ID nor the secret is in the .apk. Both come back from the Synergy Director response (<code>clientId</code> / <code>clientSecret</code>), so EA can rotate them without shipping an update</p>
<p>Now, you can ask EA what a token actually represents with <code>tokeninfo</code></p>
<pre><code class="language-plaintext">GET https://accounts.ea.com/connect/tokeninfo?access_token=&lt;access_token&gt;
Accept: */*
X-Check-Underage: true
X-Include-Authenticators: true
X-Include-StopProcess: true
</code></pre>
<pre><code class="language-javascript">{
    "authenticators": [
        { "authenticator_pid_id": &lt;pid_id&gt;, "authenticator_type": "AUTHENTICATOR_ANONYMOUS" },
        { "authenticator_pid_id": &lt;pid_id&gt;, "authenticator_type": "NUCLEUS" },
        { "authenticator_pid_id": &lt;pid_id&gt;, "authenticator_type": "AUTHENTICATOR_GOOGLE" }
    ],
    "client_id": "candcwarzone-2016-android-client",
    "expires_in": 3599,
    "is_underage": false,
    "persona_id": &lt;persona_id&gt;,
    "pid_id": "&lt;pid_id&gt;",
    "pid_type": "AUTHENTICATOR_ANONYMOUS",
    "scope": "offline basic.antelope.links.bulk openid signin antelope-rtm-readwrite search.identity social_recommendation_user basic.antelope basic.identity basic.persona basic.persona.write antelope-inbox-readwrite",
    "stopProcess": "OFF",
    "user_id": "&lt;user_id&gt;"
}
</code></pre>
<p>This one’s actually pretty telling. My single Rivals persona is backed by three authenticators: an anonymous device login, my EA (Nucleus) account and Google. The scopes also hint at the rest of the map, with <code>antelope-rtm-readwrite</code> for real-time messaging and <code>antelope-inbox-readwrite</code> for the inbox</p>
<p>The anonymous login is the <code>mobile_game_UPID</code> flow in Nimble's <code>AuthenticatorAnonymous</code> (<code>/connect/auth?mobile_login_type=mobile_game_UPID&amp;...</code>). Facebook and Google get their own authenticators, and they all end in the same <code>redirect_uri=nucleus:rest</code> code exchange. All four <code>X-</code> headers above are string constants in <code>libapp.so</code></p>
<p>The access token then shows up in two different ways depending on the service. <code>gateway.ea.com</code> wants a normal <code>Authorization: Bearer &lt;access_token&gt;</code>, while friends and groups want it in an <code>X-AuthToken</code> header alongside <code>X-Application-Key: candcwarzones-2016-android</code>. Consistent, right?</p>
<h3>Persona</h3>
<p>A persona is your in-game identity. You can fetch your own from the identity gateway</p>
<pre><code class="language-plaintext">GET https://gateway.ea.com/proxy/identity/pids/me/personas/&lt;persona_id&gt;
Authorization: Bearer &lt;access_token&gt;
X-Expand-Results: true
X-Persona-Property-Category: SERVICE_BAN_ALL
</code></pre>
<pre><code class="language-javascript">{
    "persona": {
        "dateCreated": "2018-06-24T13:12Z",
        "displayName": "sean3z#&lt;suffix&gt;",
        "isVisible": true,
        "lastAuthenticated": "2020-05-12T23:13Z",
        "name": "sean3z#&lt;suffix&gt;",
        "namespaceName": "antelope-scorpion-candcwarzones",
        "nickName": "sean3z",
        "personaId": &lt;persona_id&gt;,
        "pidId": &lt;pid_id&gt;,
        "showPersona": "EVERYONE",
        "status": "ACTIVE",
        "statusReasonCode": ""
    }
}
</code></pre>
<p>That <code>SERVICE_BAN_ALL</code> property category is a fun one to see in a routine profile call (thankfully my status still says <code>ACTIVE</code>). And yes, it's a hardcoded string in the client, so every launch asks about bans</p>
<p>You can also see how each authenticator links to the persona within the Rivals namespace</p>
<pre><code class="language-plaintext">GET https://gateway.ea.com/proxy/identity/links?personaNamespace=antelope-scorpion-candcwarzones
Authorization: Bearer &lt;access_token&gt;
</code></pre>
<p>That returns a <code>pidGamePersonaMappings</code> list with one <code>ACTIVE</code> mapping per authenticator, all pointing at the same <code>personaId</code></p>
<p>The most useful persona call, though, is the batch lookup. The game uses it to turn a list of persona IDs (say, your alliance roster) into display names</p>
<pre><code class="language-plaintext">GET https://gateway.ea.com/proxy/identity/personas?personaUri=%2Fpersonas%2F&lt;persona_id_1&gt;&amp;personaUri=%2Fpersonas%2F&lt;persona_id_2&gt;&amp;...
Authorization: Bearer &lt;access_token&gt;
Content-Type: text/plain;charset=UTF-8
</code></pre>
<p>It’s worth noting the client only ever sent about 20 <code>personaUri</code> values per request, then split the rest into another request. I'd assume that's a server-side cap. The response is a <code>personas.persona</code> array in the same shape as above</p>
<h3>Friends</h3>
<p>Friends live on <a href="http://friends.gs.ea.com">friends.gs.ea.com</a>, with separate calls for inbound and outbound invitations</p>
<pre><code class="language-plaintext">GET https://friends.gs.ea.com/friends/2/personas/&lt;persona_id&gt;/invitations/inbound?start=0&amp;count=100&amp;names=true
GET https://friends.gs.ea.com/friends/2/personas/&lt;persona_id&gt;/invitations/outbound?start=0&amp;count=100
X-Api-Version: 2
X-Application-Key: candcwarzones-2016-android
X-AuthToken: &lt;access_token&gt;
</code></pre>
<p>Both come back as <code>entries</code> plus <code>pagingInfo</code> (<code>offset</code>, <code>size</code>, <code>totalSize</code>). Mine were empty at the time</p>
<p>The friends list itself is where it gets interesting</p>
<pre><code class="language-plaintext">GET https://friends.gs.ea.com/friends/2/personas/&lt;persona_id&gt;/platforms/ea/friends
</code></pre>
<pre><code class="language-javascript">{
    "EA-GLOBAL": {
        "friends": []
    },
    "EA-INGAME": {
        "friends": [{
            "displayName": "&lt;friend&gt;#&lt;suffix&gt;",
            "nickName": "&lt;friend&gt;",
            "personaId": &lt;persona_id&gt;,
            "userId": &lt;user_id&gt;
        }]
    }
}
</code></pre>
<p>So, friends are split into two buckets. <code>EA-GLOBAL</code> would be friends from your wider EA (Origin) account, and <code>EA-INGAME</code> are the ones you added inside Rivals. All of mine were in-game (a few in-game friends, names left out here), which honestly tracks for a mobile game. Both bucket names (<code>EA-GLOBAL</code>, <code>EA-INGAME</code>) are constants in <code>libapp.so</code>, so the client knows about both even though I only ever had in-game friends</p>
<h3>Alliance</h3>
<p>Alliances are EA “groups” of type <code>ScorpionCI</code>. You can look up which alliance you're in like so</p>
<pre><code class="language-plaintext">GET https://groups.gameservices.ea.com/group/instance?pagesize=1&amp;pagestart=0&amp;typeId=ScorpionCI&amp;userId=&lt;persona_id&gt;
X-Acting-UserId: &lt;persona_id&gt;
X-Acting-UserType: NUCLEUS_PERSONA
X-Api-Version: 2
X-Application-Key: candcwarzones-2016-android
X-AuthToken: &lt;access_token&gt;
</code></pre>
<pre><code class="language-javascript">[{
    "_id": "&lt;alliance_guid&gt;",
    "name": "𝕋𝕀𝔹𝔼ℝ𝕀𝔸ℕ 𝕊𝕌ℕ",
    "r": "Founder"
}]
</code></pre>
<p>That’s my alliance (yes, the fancy Unicode name came through intact), and <code>r</code> is my role. I founded Tiberian Sun back during the Alpha release, so Founder it is. <code>ScorpionCI</code> isn't hardcoded in the client at all. The game server hands it over in <code>InitializeResponse.groupType</code> (more on <code>init</code> below), so EA could point Rivals at a different group type without an update</p>
<p>There’s also a call for join requests waiting on approval, which was an empty array for me</p>
<pre><code class="language-plaintext">GET https://groups.gameservices.ea.com/group/instance/pendingApproval?pagestart=0&amp;pagesize=20&amp;userId=&lt;persona_id&gt;
</code></pre>
<p>And the full details, roster included</p>
<pre><code class="language-plaintext">GET https://groups.gameservices.ea.com/group/instance/&lt;alliance_guid&gt;/members?pagestart=0&amp;pagesize=30&amp;groupConfig=true
</code></pre>
<pre><code class="language-javascript">{
    "_id": "&lt;alliance_guid&gt;",
    "attributes": {
        "description": "Welcome back Commander_ &lt;discord link&gt; Masters 2 or higher required to join",
        "env2": "prod",
        "groupcode": "&lt;group_code&gt;",
        "iconid": "3",
        "lastactive": "1589323671",
        "locationid": "2",
        "minplayerlevel": 60,
        "type2": "1"
    },
    "creator": &lt;persona_id&gt;,
    "dateCreated": 1532180693849,
    "groupTypeId": "ScorpionCI",
    "lastAccessDate": 1589241600000,
    "maxSize": 30,
    "memberList": [
        { "groupTypeId": "ScorpionCI", "groupguid": "&lt;alliance_guid&gt;", "id": &lt;persona_id&gt;, "r": "Founder", "since": 1532180693849, "ts": 1532180693849 },
        { "groupTypeId": "ScorpionCI", "groupguid": "&lt;alliance_guid&gt;", "id": &lt;persona_id&gt;, "r": "Leader", "since": 1535656810345, "ts": 1535656810345 },
        { "groupTypeId": "ScorpionCI", "groupguid": "&lt;alliance_guid&gt;", "id": &lt;persona_id&gt;, "r": "Member", "since": 1585082055943, "ts": 1585082055943 }
    ],
    "name": "𝕋𝕀𝔹𝔼ℝ𝕀𝔸ℕ 𝕊𝕌ℕ",
    "override": {
        "joinConfig": {
            "canInviteToJoin": true,
            "canUserRequestMembership": false,
            "isFreeJoin": true,
            "isPwdProtected": false
        }
    },
    "shortName": "Tiberian Sun",
    "size": 28
}
</code></pre>
<p>A few things jump out. Roles are <code>Founder</code>, <code>Leader</code> and <code>Member</code> (all three are string constants in the client), <code>maxSize</code> is 30, and every timestamp is in epoch milliseconds (except <code>lastactive</code>, which is seconds, because of course it is). Most attributes also show up twice with a <code>2</code> suffix (<code>description2</code>, <code>iconid2</code>, <code>minplayerlevel2</code>). I originally guessed that was a migration that never got cleaned up. Half right: <code>description2</code> and friends appear right next to the originals in <code>libapp.so</code>, so the client still reads and writes both sets. Whatever the migration was, it never finished</p>
<p>The game server also has its own idea of an alliance. Its protos call them guilds (<code>PlayerGuildData</code> with <code>guildId</code>, <code>guildName</code>, <code>iconId</code>, <code>locationId</code>, <code>currentMemberCount</code>, <code>maxMemberCount</code>), which is why the game server and EA's social platform use different names for the same thing</p>
<p>Notice the member list only gives you persona IDs, though. That’s where the batch persona lookup from earlier comes in, and it’s exactly how the client turns a roster into names</p>
<h3>Game server (protobuf)</h3>
<p>Now for the main event. Everything gameplay-related goes to <a href="http://prod.scorpion-ea.com">prod.scorpion-ea.com</a>, and nearly every request looks something like this</p>
<pre><code class="language-plaintext">POST https://prod.scorpion-ea.com/&lt;method&gt;
charset: UTF-8
CONFIG-HASH: &lt;config_hash&gt;
Accept: application/x-protobuf
Content-Type: application/x-protobuf
SESSION-ID: &lt;session_id&gt;
COOKIE: AWSALB=&lt;awsalb_cookie&gt;
EADP-PERSONA-ID: &lt;persona_id&gt;
MINOR-VERSION: 8
X-Scorpion-Request-Latency: &lt;previous_method&gt; &lt;epoch_ms&gt; &lt;latency_ms&gt;
User-Agent: osiris Dalvik/2.1.0 (Linux; U; Android 10; Pixel 3 Build/QQ2A.200405.005)
</code></pre>
<p><code>Accept: application/x-protobuf</code> means the bodies are Protocol Buffers, a compact binary format. Without the .proto schema files, the field names and types are a mystery, so all you get is field numbers, lengths and whatever strings happen to be readable. That's the honest limit of what I could decode back in 2020</p>
<p><code>X-Scorpion-Request-Latency</code> is a neat one too. It looks like the client reports the previous call's name, timestamp and round-trip time (e.g. <code>purchaseCard ... 675</code>) on the next request, so roughly 600–850 ms per call back then. That's nothing to brag about, but it's not terrible for a mobile game either. <code>AWSALB</code> is just the AWS load balancer's sticky-session cookie</p>
<h3>2026: opening the .apk properly</h3>
<p>This is where revisiting the binary paid off. The fonts from 2020 check out (<code>Celdum-Bold.otf</code> plus Bold, Regular and Semibold <code>DaytonaPro</code>), and so do the asset formats. There are 808 <code>.sb</code>, 369 <code>.sba</code> and 114 <code>.sb3d</code> files in <code>assets/published</code>, plus 243 <code>.sbfx</code> files</p>
<p>The Firebase guess was wrong though. The app pulls in Firebase Analytics, Crashlytics and Cloud Messaging (push), but not the Realtime Database SDK. There’s a <code>firebase_database_url</code> in the resources, but it points at a project called <code>test-scorpion-12716110</code>, which looks like a leftover from the default Firebase config. Matches are played over a WebSocket, which we'll get to</p>
<p>The bigger reason I called the .apk a dead end in 2020 is that the Java code is mostly a shell. It’s EA’s Nimble SDK, Facebook, AWS and friends. The actual game is a 64 MB native library, <code>lib/arm64-v8a/libapp.so</code>, built on EA's in-house IronMonkey engine. And that's where things got interesting, because the game server's protobuf schemas are compiled right into it</p>
<p>Protobuf schemas normally stay on the developer’s machine, but C++ protobuf (the full runtime, not “lite”) compiles each <code>.proto</code> file into the binary as a serialized <code>FileDescriptorProto</code>. That's how reflection and debug printing work. <code>libapp.so</code> has 108 of them sitting in plain sight, from <code>protocol/service.proto</code> to <code>data/player_data.proto</code></p>
<p>Recovering them is mostly bookkeeping. Find bytes that look like <code>0x0A &lt;len&gt; "something.proto"</code> (field 1 of a <code>FileDescriptorProto</code> is its file name), walk the protobuf fields from there until something stops parsing, then print the descriptor back out as <code>.proto</code> text. I did it with a ~150-line Perl script, but tools like pbtk do the same thing</p>
<p>The best part is <code>protocol/service.proto</code>, which declares the whole game server</p>
<pre><code class="language-c">service ScorpionService {
  rpc init(InitializeRequest) returns (InitializeResponse);
  rpc getPlayerState(GetPlayerStateRequest) returns (GetPlayerStateResponse);
  rpc findMatch(FindMatchRequest) returns (FindMatchResponse);
  rpc purchaseCard(PurchaseCardRequest) returns (DynamicPurchaseResponse);
  rpc donateCards(DonateCardsRequest) returns (DonateCardsResponse);
  rpc startConvoy(EmptyMessage) returns (StartConvoyResponse);
  // ...72 RPCs in total
}
</code></pre>
<p>Every method carries two custom options, <code>option_http_verb</code> (always <code>"POST"</code>) and <code>option_modified_resources</code> (<code>"player"</code> and/or <code>"client"</code>, so the client knows which cached state to refresh afterwards). And each RPC name is literally the URL path, <code>POST /findMatch</code> and so on</p>
<p>The headers check out too. <code>CONFIG-HASH</code>, <code>SESSION-ID</code>, <code>EADP-PERSONA-ID</code>, <code>MINOR-VERSION</code> and <code>X-Scorpion-Request-Latency</code> are all string constants in the client. <code>SESSION-ID</code> and <code>CONFIG-HASH</code> come straight from the <code>init</code> response (<code>sessionId</code> and <code>gameConfigHash</code>), and <code>MINOR-VERSION: 8</code> is the 8 in version 1.8. There's also an <code>X-Scorpion-RequestId</code> header that never showed up in my captures</p>
<p>With the schemas in hand, I went back to the 2020 dump and re-read every method I’d captured. Here’s that list, now with their real message types</p>
<ul>
<li><code>POST /init</code> — Session bootstrap (<code>InitializeRequest</code> → <code>InitializeResponse</code>)</li>
<li><code>GET /mapIp</code> — Returns your region as plain text (e.g. <code>US</code>), not protobuf</li>
<li><code>POST /findMatch</code> — Enter matchmaking (<code>FindMatchRequest</code> → <code>FindMatchResponse</code>)</li>
<li><code>POST /startClones</code> / <code>POST /collectClones</code> — Cloning chamber (<code>StartClonesRequest</code> / <code>CollectClonesRequest</code> → <code>*Response</code>)</li>
<li><code>POST /purchaseCard</code> — Buy unit cards (<code>PurchaseCardRequest</code> → <code>DynamicPurchaseResponse</code>)</li>
<li><code>POST /donateCards</code> — Donate cards to an alliance member (<code>DonateCardsRequest</code> → <code>DonateCardsResponse</code>)</li>
<li><code>POST /getGuildTrophies</code> — Alliance trophy counts (<code>GetGuildTrophiesRequest</code> → <code>GetGuildTrophiesResponse</code>)</li>
<li><code>POST /startConvoy</code> / <code>POST /fuelRushConvoy</code> — Convoy start and speed-up (<code>EmptyMessage</code> → <code>StartConvoyResponse</code> / <code>FuelRushConvoyResponse</code>)</li>
</ul>
<p><strong>init.</strong> This is the first call, and the payload carries the access token along with client details. The readable bits include the client ID (<code>candcwarzone-2016-android-client</code>), a game version string (1.8.x), an SDK version (1.42.0.x), <code>nimble</code> (EA's mobile SDK), the locale <code>en_US</code> and a device ID</p>
<p><code>InitializeRequest</code> has the version split out (<code>majorVersion</code>, <code>minorVersion</code>, <code>patchVersion</code>, <code>hotfixVersion</code>), the access token as <code>eadpSessionToken</code>, your <code>personaId</code>, and a <code>PinHeaders</code> message. That's where all those readable strings live. <code>PinHeaders</code> is EA's telemetry header block, with the client ID (<code>tid</code>), game version (<code>v</code>), SDK version and type (<code>sdkv</code>, <code>sdkt</code> = nimble), locale (<code>loc</code>) and a <code>didm</code> map of device IDs (<code>androidid</code>, <code>gaid</code>, <code>eadeviceid</code> and friends)</p>
<p>The response is the real prize. It has your entire <code>PlayerData</code>, the <code>sessionId</code> and <code>gameConfigHash</code> you'll send on every later call, a <code>gameConfigURL</code> to download the game balance data, the <code>groupType</code> (<code>ScorpionCI</code>), and a <code>ServerApplicationProperties</code> block with the battle-service hosts, the replay storage location and <code>dlcBaseUrl</code></p>
<p><strong>mapIp.</strong> The simplest call of the bunch. <code>GET /mapIp</code> with no body returns <code>US</code>, and the client uses it to pick a region. <code>https://prod.scorpion-ea.com/mapIp</code> is hardcoded in <code>AppSettings.cpp</code>. It's not part of <code>ScorpionService</code>, which explains why it's the one GET in the bunch</p>
<p><strong>findMatch.</strong> This is the one I was most excited about back in 2020, because your deck is right there in the request. Pulling out just the readable strings</p>
<pre><code class="language-plaintext">Cmdr_Gdi_Solomon
Unit_Gdi_Riflemen
Unit_Gdi_RocketTroopers
Unit_Gdi_JumpTroopers
Unit_Gdi_Pitbull
Unit_Gdi_Talon
Unit_Gdi_Orca
prod.us-east-1.battle-service.scorpion-ea.com
prod.eu-central-1.battle-service.scorpion-ea.com
</code></pre>
<p>That’s a commander plus six units (my GDI deck at the time), along with the battle-service hosts the client is willing to play on. Unit IDs follow a <code>Unit_&lt;Faction&gt;_&lt;Name&gt;</code> pattern and commanders follow <code>Cmdr_&lt;Faction&gt;_&lt;Name&gt;</code>, which is exactly what you'd need for deck-level stats</p>
<p>The response is kind enough to tell you what it is in the headers</p>
<pre><code class="language-plaintext">X-Protobuf-Schema: protocol/matchmaking.proto
X-Protobuf-Message: ws.app.proto.FindMatchResponse
</code></pre>
<p>Thankfully, that at least gives us the message name, even without the schema. The readable parts of <code>FindMatchResponse</code> are a match ID, a fresh load balancer cookie, the battle-service base URL, a couple of GUIDs, a WebSocket URL (<code>wss://prod.us-east-1.battle-service.scorpion-ea.com/ws</code>), the region (<code>us-east-1</code>) and a queue name shaped like <code>matchmakingqueue-us-east-1-#&lt;id&gt;-1.8-RegularGame</code>. So, matchmaking happens over REST, and the actual match is played over a WebSocket to the battle service</p>
<p>And now we have the schema. <code>protocol/matchmaking.proto</code> is one of the recovered files, and it matches the header exactly</p>
<pre><code class="language-c">message FindMatchRequest {
  int32 numberOfUsers = 1;
  int32 retryCount = 4;
  Deck selectedDeck = 5;
  Enums.MatchType matchType = 6;
  string debugMapChoice = 7;
  repeated string battle_service_hosts = 8;
  string eventId = 9;
  string debugBucketNameSuffix = 10;
}

message FindMatchResponse {
  Status status = 1;                 // Success, AlreadyInGame
  string matchToken = 2;             // the "match ID"
  string lbCookie = 3;               // replayed as AWSALB= on the WebSocket
  string battle_service_dns_name = 4;
  string instance_guid = 5;          // GUID #1
  string player_match_token = 6;     // GUID #2
  string client_connection_url = 7;  // wss://.../ws
  string aws_region = 8;
  string bucket_name = 9;            // the queue name
  int32 min_trophies = 10;
  int32 max_trophies = 11;
}
</code></pre>
<p>A deck is <code>Deck { commanderNameId = 1; buildingNameIds = 2; unitIds = 3; }</code>. The <code>RegularGame</code> in the queue name lines up with <code>Enums.MatchType</code>, which has <code>Regular</code>, <code>EVENT</code>, <code>FRIENDLY</code> and <code>CUSTOM</code>. Also notice <code>debugMapChoice</code> and <code>debugBucketNameSuffix</code>, which are leftovers from internal testing</p>
<p><strong>Cloning chamber.</strong> <code>startClones</code> takes a chamber name and a unit, which in my case was <code>free_cloning_chamber</code> and <code>Unit_Gdi_Riflemen</code>. The response echoes those back with a GUID for the job and a timer type of <code>StandardTimed</code>. <code>collectClones</code> just sends that job GUID back when it's done</p>
<p>Spot on against the schema. <code>StartClonesRequest</code> is <code>{ cloningChamberId, unitId }</code> and <code>CollectClonesRequest</code> is <code>{ activeChamberId }</code>. The GUID is the key into <code>CloningLab.activeChambers</code>, a map of in-progress chambers (<code>unitId</code>, <code>numBattlesRequired</code>, <code>numBattlesCompleted</code>, <code>quantityToReceive</code>, <code>startTimeMs</code>, <code>endTimeMs</code>). There isn't a timer-type field anywhere though, so <code>StandardTimed</code> is most likely the chamber's <code>cloningChamberConfigId</code>. In other words, the free chamber runs the "standard timed" config</p>
<p><strong>purchaseCard.</strong> This was 160 credits for 10 units, and the request body is tiny. It’s basically just the unit ID</p>
<pre><code class="language-plaintext">Unit_Gdi_Hammerhead
</code></pre>
<p>The response, on the other hand, is huge. Back in 2020 I thought the server was dumping a big slice of player state after every action. Readable strings in there include</p>
<pre><code class="language-plaintext">Unit_Gdi_Hammerhead
free_cloning_chamber / Unit_Gdi_Riflemen / StandardTimed
daily_battle_bonus
Ent_CommanderSkin_Cmdr_Gdi_Jackson_Wildfront
Ent_UnitSkin_Unit_Nod_Widowmaker_ArcticWhiteSkin
Ent_UnitSkin_Unit_Nod_FlameTroopers_ArcticWhiteSkin
Unit_Nod_Venom, Unit_Gdi_Disruptor, Cmdr_Nod_Seth, Unit_Gdi_MSV, Unit_Nod_ChemicalWarrior
promoLevelT05, promoOneTime, promoLevelT10, promoLapsedSpenderDay28, promoCmdrSkinJacksonWildfront
Unit_Gdi_MammothTank, Unit_Nod_FlameTank, Unit_Gdi_Titan
</code></pre>
<p>So, in one response you get the cloning chamber state, the daily battle bonus, owned skins (<code>Ent_</code> entitlements), what looks like the store's card rotation and a list of active promos. <code>promoLapsedSpenderDay28</code> is a pretty candid name for a promo, and I'll let you draw your own conclusions there</p>
<p>Close, but it’s not a general player-state dump. <code>PurchaseCardRequest</code> is <code>{ itemDefinitionId, regularStorefrontIndex }</code>, so it's the unit ID plus which store slot you tapped. The response is a <code>DynamicPurchaseResponse</code>, which has three parts</p>
<ul>
<li><code>OpenRewardResponse</code>: everything the purchase touched. That's your updated wallet, unit progressions (hence all the unit IDs), the cloning lab, player boosts (<code>daily_battle_bonus</code> fits there) and entitlements (the <code>Ent_</code> skins)</li>
<li><code>updatedDynamicStorefront</code>: the store's card rotation (<code>cardPackIds</code>) and per-offer purchase counts keyed by offer ID, which is where the <code>promo*</code> names come from</li>
<li><code>updatedWallet</code></li>
</ul>
<p>The game just sends back every collection the purchase could have changed. As for the currency, the <code>Wallet</code> message has <code>premium</code>, <code>credits</code>, <code>fuel</code>, <code>tickets</code>, <code>dataChips</code>, <code>eventCurrency</code>, <code>supplies</code> and <code>battlePoints</code>, and card purchases come out of <code>credits</code></p>
<p><strong>donateCards.</strong> Donation requests are identified by a string shaped like this</p>
<pre><code class="language-plaintext">donationRequest_prod-{&lt;alliance_guid&gt;}-&lt;request_id&gt;
</code></pre>
<p>The request sends one of those IDs plus a small number (the card count, I believe). Back then I thought the response included the same player-state blob as above, plus every open donation request in the alliance</p>
<p>The card count guess is right, since the field is literally <code>numberOfCardsToAttemptDonation</code>. The response is smaller than I thought though. <code>DonateCardsResponse</code> has your reward, <code>cardsSuccessfullyDonated</code>, the request's updated count, your updated unit progressions, <code>playerLevel</code>, <code>currentExperience</code> and <code>DailyData</code>. Those donation request IDs come from <code>DailyData.donationRequestIdToExpiringAmountDonated</code>, which is every request <em>you've</em> donated to today (it powers the daily donation cap), not every open request in the alliance</p>
<p><strong>getGuildTrophies.</strong> The request contains the alliance GUID and a few small numbers, and the response repeats that GUID with what look like trophy counts. So, under the hood, alliances are “guilds” to the game server and “groups” to EA’s social platform</p>
<p>Confirmed by the schema. <code>GetGuildTrophiesRequest</code> is <code>{ repeated LeaderboardType types; repeated string guildIds; }</code>, and the small numbers are leaderboard types (<code>TrophiesAll</code> = 1, <code>TrophiesGdi</code> = 2, <code>TrophiesNod</code> = 3, <code>GuildTrophiesAll</code> = 4, and so on). The response maps each type to a <code>guildId → trophies</code> map</p>
<p><strong>Convoys.</strong> <code>startConvoy</code> and <code>fuelRushConvoy</code> both send an empty body (<code>Content-Length: 0</code>) and get back a short opaque message. There's no readable string in either, so in 2020 I could only tell you they exist</p>
<p>Both take <code>EmptyMessage</code>, and an empty protobuf message encodes to zero bytes, hence the <code>Content-Length: 0</code>. The responses are numbers only, which is why I couldn't read them. <code>StartConvoyResponse</code> is the updated <code>PlayerConvoyPool</code> plus your wallet, and <code>FuelRushConvoyResponse</code> adds the <code>completionRewards</code>. "Fuel rush" means spending fuel (<code>Wallet.fuel</code>) to finish a convoy immediately. There's also a <code>completeConvoy</code> for letting one finish on its own, with an <code>alwaysSetMeToTrue</code> field that I just have to point out</p>
<h3>The other 60-odd methods I never captured</h3>
<p>Bounties (<code>completeBounty</code>, <code>claimBountyChest</code>, <code>reRollBounty</code>, <code>refreshAllBounties</code>), progression (<code>upgradeItem</code>, <code>openCompletedFreeChest</code>, <code>claimExperienceLevelUpReward</code>, <code>purchaseExperienceLevel</code>, <code>battleTheaterLevelUpReward</code>, <code>completeSeason</code>), the store (<code>purchaseStaticStoreReward</code>, <code>purchasePromotionalOffer</code>, <code>purchaseUnitCrate</code>, <code>purchaseDynamicCrate</code>, <code>purchasePlayerBoost</code>, <code>claimReceipt</code>, <code>openVault</code>), alliances (<code>createGuild</code>, <code>refreshGuild</code>, <code>getDonationCountsForRequests</code>, <code>requestDonation</code>, <code>checkMailbox</code>, <code>processPlayerMailbox</code>), friendly and custom battles (<code>hostFriendlyBattle</code>, <code>joinFriendlyBattle2</code>, <code>createCustomGame</code>, <code>joinCustomGame</code>), events and races (<code>startEventRun</code>, <code>claimEventReward</code>, <code>retireEventRun</code>, <code>collectRaceReward</code>, <code>completeRace</code>, <code>checkRaceState</code>, <code>checkRaceLeaderboard</code>), social (<code>leaderboards</code>, <code>getPlayerTrophies</code>, <code>getPlayerProfile</code>, <code>getFeedData</code>, <code>updateLike</code>, <code>getFriendsTopWeeklyStats</code>, <code>getTvLogByLeague</code>), replays (<code>shareReplay</code>, <code>saveReplay</code>, <code>unsaveReplay</code>), and a handful of housekeeping calls like <code>desyncLogSave</code>, <code>perfReportLogSave</code>, <code>updateClientData</code>, <code>collectDailyReward</code> and <code>deleteAppleAccount</code></p>
<h3>Inbox</h3>
<p>The in-game inbox comes from EA’s engagement service</p>
<pre><code class="language-plaintext">POST https://pin-em.data.ea.com/em/v4/action
Content-Type: application/json
um_version: v4
x-ea-env: production
</code></pre>
<p>The request body is JSON, with your age, country, language and platform, a <code>didm</code> block of device IDs (<code>&lt;device_ids&gt;</code>), a <code>pidm</code> block of account IDs and a list of trigger IDs (<code>inbox_all_msgs</code> in this case). The response is a list of messages, each with a title, body, image URLs, a link and a start and end date</p>
<p>Mine were all marketing messages, like “Establishing Twitter Control” pointing at @CnCRivals and the original “Welcome to Command &amp; Conquer: Rivals!” letter. Each message also ships with tracking URLs for impressions, clicks, conversions and errors, so this is very much a marketing pipe rather than a mailbox</p>
<p>Internally this is “Aruba”, EA’s engagement manager. The director key is <code>pin.aruba.url</code>, the path constant is <code>/action</code>, and <code>init</code> even forwards <code>arubaClientAttributes</code> to the game server. <code>didm</code> and <code>pidm</code> are the same <code>DeviceIdMap</code> and <code>PlayerIdMap</code> that show up in the PIN telemetry protos, so the inbox and telemetry share one identity format. That's also a pretty clear sign the inbox is built on the telemetry stack</p>
<h3>The battle service (the part I missed)</h3>
<p>I never captured a single byte from the battle service in 2020, and I always assumed I’d just messed up the capture. The .apk explains it</p>
<p>Two things. The WebSocket isn’t opened through Java at all. It’s EA’s DirtySDK (<code>ProtoWebSocket</code> on top of <code>ProtoSSL</code>), which opens its own native sockets and ignores the phone's Wi-Fi proxy setting, so that traffic most likely never went near mitmproxy. Even if it had, ProtoSSL does its own certificate checks against a built-in CA list, topped up by the four certificates in <code>assets/published/certs</code> (Amazon and Starfield roots), so a mitmproxy CA wouldn't have passed</p>
<p>The protocol is in <code>protocol/match_session.proto</code>. The client opens <code>client_connection_url</code> (sending <code>lbCookie</code> back as <code>AWSALB=</code>) and sends a <code>ConnectToSession</code> with the match tokens. From then on, every message is a <code>ClientTransportMessage</code> or <code>ServerTransportMessage</code>. The server can upgrade you to UDP (<code>Connected.udpConnectionHostname</code>/<code>udpConnectionPort</code>). The game itself is deterministic lockstep. Clients only send commands (<code>SquadMoveCommand</code>, <code>PurchaseUnitCommand</code>, <code>UseUnitAbilityCommand</code>, <code>SurrenderCommand</code> and so on), the server relays them with a <code>NetTick</code>, and both clients periodically send a <code>GameHash</code> so the server can catch desyncs (<code>DesyncDetected</code>)</p>
<p>And yes, <code>DebugSpawnCommand</code>, <code>DebugKillCommand</code> and <code>DebugDepositTiberiumCommand</code> are in the shipping protocol. No, I didn't try them</p>
<h3>Building the tracker</h3>
<p>So, back to what I was really after: deck-level stats. With <code>findMatch</code> you can see exactly which commander and units go into every match, and I assumed the results were only available over the battle-service WebSocket. The protos say otherwise, and it makes this a whole lot easier</p>
<pre><code class="language-javascript">// data/player_data.proto
message PlayerData {
  ...
  BattleLog battleLog = 22;
  ...
}

message BattleLog {
  repeated BattleLogEntry battleLogEntries = 1;
}

message BattleLogEntry {
  string winningPersonaId = 3;
  string matchGuid = 4;
  int64 matchTime = 5;
  int32 majorVersion = 6;
  int32 minorVersion = 7;
  repeated BattleLogEntryParticipant participants = 8;
  string mapId = 12;
  Enums.MatchType matchType = 15;
  ...
}

message BattleLogEntryParticipant {
  string personaId = 1;
  string playerName = 2;
  int32 trophiesBeforeMatch = 3;
  Deck deck = 4;
  PlayerGuildData guildData = 7;
  int32 trophyChangeFromMatch = 8;
  int32 playerLevel = 9;
  bool isBot = 16;
  ...
}
</code></pre>
<p>That’s the in-game battle log, and it has both decks, both players, the trophy swing and the winner for every recent match. It rides along inside <code>PlayerData</code>, which comes back from <code>init</code> (every launch), <code>getPlayerState</code>, <code>getPlayerProfile</code> and <code>refreshGuild</code>. All of those are plain REST calls to <code>prod.scorpion-ea.com</code>, the same traffic mitmproxy could already see. So, no WebSocket required</p>
<p>(Fun aside: <code>PlayerData.progression.player_stats.currentSeasonDeckStats</code> is a map of <code>Deck</code> → wins/losses. The server already tracks per-deck records for the season. It just doesn't show you)</p>
<p>The plan, then</p>
<ol>
<li>A small HTTPS proxy that only decrypts <code>prod.scorpion-ea.com</code>. Everything else, including EA logins and the battle service, is passed through as an untouched TCP tunnel. I don't want my tracker anywhere near account tokens</li>
<li>Decode the battle log out of any response that carries <code>PlayerData</code></li>
<li>Store each match once (keyed by <code>matchGuid</code>) in SQLite, from my point of view</li>
<li>Run some SQL</li>
</ol>
<p>I developed this in C++, with OpenSSL for TLS, Asio for sockets, zlib for gzip and SQLite for storage, all from vcpkg. It's about 900 lines, so I'll just hit the highlights here. It builds cleanly with MSVC (on Windows, from an x64 Native Tools command prompt) and passes its tests, including an end-to-end run through the proxy</p>
<h3>Decoding without generated code</h3>
<p>I could run the recovered <code>.proto</code> files through <code>protoc</code>, but I only need about 20 fields. A protobuf message is just a list of <code>(field number, wire type, value)</code> triples, so a tiny reader plus the field numbers from the schema does the job</p>
<pre><code class="language-cpp">BattleLogEntry decode_entry(std::string_view bytes) {
    BattleLogEntry e{.raw = std::string{bytes}};
    pw::Reader r{bytes};
    while (auto f = r.next()) {
        switch (f-&gt;number) {
        case 3: e.winning_persona_id = f-&gt;bytes; break;
        case 4: e.match_guid = f-&gt;bytes; break;
        case 5: e.match_time = f-&gt;i64(); break;
        case 6: e.major_version = f-&gt;i32(); break;
        case 7: e.minor_version = f-&gt;i32(); break;
        case 8: e.participants.push_back(decode_participant(f-&gt;message())); break;
        case 12: e.map_id = f-&gt;bytes; break;
        case 15: e.match_type = f-&gt;i32(); break;
        }
    }
    return e;
}
</code></pre>
<p>Unknown fields are skipped, so if EA adds fields in a later version nothing breaks. The raw entry bytes are kept in the database too, so I can re-decode old matches if I want more fields later</p>
<p>Figuring out which response is which is easy, since the server says so itself. The proxy reads <code>X-Protobuf-Message</code> (falling back to the URL path) and looks up which field holds <code>PlayerData</code></p>
<pre><code class="language-cpp">static const std::map&lt;std::string_view, std::uint32_t, std::less&lt;&gt;&gt; fields{
    {"InitializeResponse", 2},        {"init", 2},
    {"GetPlayerStateResponse", 2},    {"getPlayerState", 2},
    {"GetPlayerProfileResponse", 2},  {"getPlayerProfile", 2},
    {"RefreshGuildResponse", 1},      {"refreshGuild", 1},
};
</code></pre>
<p>“Me” is the <code>EADP-PERSONA-ID</code> request header. When importing a saved response with no headers, it's the one persona that shows up in every entry of the log</p>
<h3>The proxy</h3>
<p>It’s a standard <code>CONNECT</code> proxy. For hosts on the intercept list, it answers the TLS handshake with a certificate minted on the fly from a local CA, opens its own properly verified TLS connection to the real server, and shuttles HTTP/1.1 messages back and forth byte-for-byte. A decoded copy (de-chunked, gunzipped) goes to the recorder. Every other host just gets two sockets glued together</p>
<pre><code class="language-cpp">if (req-&gt;method() == "CONNECT") {
    auto [host, port] = split_authority(req-&gt;target(), "443");
    asio::write(client, asio::buffer(std::string_view{"HTTP/1.1 200 Connection Established\r\n\r\n"}));
    if (intercept_.contains(host)) return intercept(client, host, port);

    tcp::socket upstream{io_};
    asio::connect(upstream, tcp::resolver{io_}.resolve(host, port));
    return tunnel(client, upstream);
}
</code></pre>
<p>If you set up mitmproxy from my earlier post, the tracker picks up <code>~/.mitmproxy/mitmproxy-ca.pem</code> automatically, so the phone side doesn't change. Otherwise it creates its own CA and writes <code>rivals-tracker-ca-cert.pem</code> for you to install</p>
<h3>Running it</h3>
<pre><code class="language-shell"># once
git clone https://github.com/microsoft/vcpkg &amp;&amp; ./vcpkg/bootstrap-vcpkg.sh
export VCPKG_ROOT=$PWD/vcpkg

cd rivals-tracker
cmake --preset default
cmake --build --preset default
ctest --preset default

./build/rivals-tracker proxy --port 8080 --db rivals.db
</code></pre>
<p>Point the phone’s Wi-Fi proxy at your machine on port 8080 and launch the game. On launch you’ll see something like</p>
<pre><code class="language-plaintext">using CA rivals-tracker-ca.pem
listening on 0.0.0.0:8080 (intercepting: {"prod.scorpion-ea.com"})
POST /init -&gt; 200 (204838 bytes)
  WIN  vs Oh Zone (250 trophies)  Cmdr_Nod_Kane Unit_Nod_Fanatic Unit_Nod_Scarab Unit_Nod_CatalystGunship Unit_Nod_FireBomber Unit_Nod_Viper Unit_Nod_Artillery
  WIN  vs RaTheSunGod076 (314 trophies)  Cmdr_Gdi_Liang Unit_Gdi_Riflemen Unit_Gdi_RocketTroopers Unit_Gdi_JumpTroopers Unit_Gdi_Robodogs Unit_Gdi_MohawkGunship Unit_Gdi_Sandstorm
  WIN  vs Heckler &amp; Koch (709 trophies)  Cmdr_Nod_Kane Unit_Nod_StormTroopers Unit_Nod_FlameTroopers Unit_Nod_Buggy Unit_Nod_TickTank Unit_Nod_Banshee Unit_Nod_Avatar
  WIN  vs Gooders 21 (636 trophies)  Cmdr_Gdi_Solomon Unit_Gdi_Riflemen Unit_Gdi_RocketTroopers Unit_Gdi_Grenadier Unit_Gdi_Wolverine Unit_Gdi_ZoneTrooper Unit_Gdi_Kodiak
  WIN  vs Alceu (272 trophies)  Cmdr_Nod_Seth Unit_Nod_ChemQuad Unit_Nod_BeamCannon Unit_Nod_Banshee Unit_Nod_Confessor Unit_Nod_Rockwyrm Unit_Nod_Cyborg
  WIN  vs Gooders 21 (645 trophies)  Cmdr_Gdi_Solomon Unit_Gdi_Riflemen Unit_Gdi_RocketTroopers Unit_Gdi_Grenadier Unit_Gdi_Wolverine Unit_Gdi_ZoneTrooper Unit_Gdi_Kodiak
  WIN  vs Gooders 21 (635 trophies)  Cmdr_Gdi_Solomon Unit_Gdi_DroneSwarm Unit_Gdi_Talon Unit_Gdi_MohawkGunship Unit_Gdi_Wolverine Unit_Gdi_ZoneTrooper Unit_Gdi_Sandstorm
  WIN  vs Dennis (700 trophies)  Cmdr_Nod_Seth Unit_Nod_StormTroopers Unit_Nod_Scarab Unit_Nod_MutantMarauder Unit_Nod_AttackBike Unit_Nod_ChemQuad Unit_Nod_ScorpionTank
  WIN  vs D3K4N000K (629 trophies)  Cmdr_Gdi_Strongarm Unit_Gdi_Riflemen Unit_Gdi_RocketTroopers Unit_Gdi_Grenadier Unit_Gdi_Talon Unit_Gdi_Orca Unit_Gdi_Sandstorm
  WIN  vs SilentDrengr818 (850 trophies)  Cmdr_Gdi_Liang Unit_Gdi_Riflemen Unit_Gdi_Rhino Unit_Gdi_Pitbull Unit_Gdi_PredatorTank Unit_Gdi_Talon Unit_Gdi_ZoneTrooper

  recorded 10 new match(es) from init
</code></pre>
<p>Since the battle log only comes down with <code>PlayerData</code>, new matches land the next time the game calls <code>init</code> (or one of the other three). In practice that means restarting the game every so often, before the log rolls over</p>
<h3>Stats</h3>
<p>Then the fun part</p>
<pre><code class="language-plaintext">./build/rivals-tracker stats --min-games 3
10 matches recorded, 10 wins (100.0%)

By my deck
                                                                games   wins   win %
  Cmdr_Gdi_Solomon,Unit_Gdi_JumpTroopers,Unit_Gdi_Orca,Unit_Gdi_Pitbull,Unit_Gdi_Riflemen,Unit_Gdi_RocketTroopers,Unit_Gdi_Talon
                                                                   10     10  100.0%

Against opponent commander
                                                                games   wins   win %
  Cmdr_Gdi_Liang                                                    2      2  100.0%
  Cmdr_Gdi_Solomon                                                  3      3  100.0%
  Cmdr_Gdi_Strongarm                                                1      1  100.0%
  Cmdr_Nod_Kane                                                     2      2  100.0%
  Cmdr_Nod_Seth                                                     2      2  100.0%

Against opponent unit (worst first)
                                                                games   wins   win %
  Unit_Gdi_DroneSwarm                                               1      1  100.0%
  Unit_Gdi_Grenadier                                                3      3  100.0%
  Unit_Gdi_JumpTroopers                                             1      1  100.0%
  Unit_Gdi_Kodiak                                                   2      2  100.0%
  Unit_Gdi_MohawkGunship                                            2      2  100.0%
  Unit_Gdi_Orca                                                     1      1  100.0%
  Unit_Gdi_Pitbull                                                  1      1  100.0%
  Unit_Gdi_PredatorTank                                             1      1  100.0%
  Unit_Gdi_Rhino                                                    1      1  100.0%
  Unit_Gdi_Riflemen                                                 5      5  100.0%
  Unit_Gdi_Robodogs                                                 1      1  100.0%
  Unit_Gdi_RocketTroopers                                           4      4  100.0%
  Unit_Gdi_Sandstorm                                                3      3  100.0%
  Unit_Gdi_Talon                                                    3      3  100.0%
  Unit_Gdi_Wolverine                                                3      3  100.0%

Head to head
                                                                games   wins   win %
  Gooders 21                                                        3      3  100.0%

By map
                                                                games   wins   win %
  SA_02_Canal_Row                                                   3      3  100.0%
  SA_02_Two_Fuses                                                   2      2  100.0%
  SA_02_Tiberium_Stripes                                            2      2  100.0%
  SA_01_Frozen_Road                                                 2      2  100.0%
  TR_01_Three_Sentinels                                             1      1  100.0%
</code></pre>
<p>Everything’s in two tables (<code>matches</code> and <code>match_units</code>), so anything the built-in report doesn't cover is one query away. For example, "which of my decks does worst against Venom?"</p>
<pre><code class="language-sql">SELECT m.my_deck, COUNT(*) AS games, AVG(m.won) AS win_rate
FROM matches m JOIN match_units u USING (match_guid)
WHERE u.side = 'opp' AND u.unit_id = 'Unit_Nod_Venom'
GROUP BY m.my_deck ORDER BY win_rate;
</code></pre>
<p>A quick word on scope: this is strictly read-only. It never changes a request or a response, it only decrypts the one game host, and it only stores what the game already shows you in the battle log. It’s a stats notebook, not a cheat. And for now it’ll likely stay local to prevent any malicious behavior</p>
<h3>Wrap</h3>
<p>So, that’s what I was able to piece together: an unfinished 2020 dump, a 2026 trip into <code>libapp.so</code>, and a re-read of the old captures with the schemas in hand. The JSON services (auth, personas, friends, alliances) are honestly pretty approachable, and the game server turned out to be too, once I realized the schemas were sitting right there the whole time</p>
<p>It’s worth repeating that the captures are from around May 2020 and the .apk is 1.14.0, so some of the details above have certainly drifted. I’ve tested the tracker end to end against hand-built battle logs, but if EA has changed things since 1.14.0, the <code>--dump</code> flag will save every request and response body so you can check them against you own recovered protos</p>
<p>Still, I hope it’s a fun look under the hood of a game I really enjoy</p>
<p>See you on the battlefield Commander!</p>
]]></content:encoded></item><item><title><![CDATA[Efficiency is an error-budget input]]></title><description><![CDATA[Capacity is a reliability decision, and the cost of a request is how you pay for it]]></description><link>https://rambling.hashnode.dev/efficiency-is-an-error-budget-input-f89938422c09</link><guid isPermaLink="true">https://rambling.hashnode.dev/efficiency-is-an-error-budget-input-f89938422c09</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Fri, 23 Oct 2026 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/b8ca049b-7f22-49aa-b9ea-134d0e363d85.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4>Capacity is a reliability decision, and the cost of a request is how you pay for it</h4>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/c4dfbb24-02c0-443b-a594-e7f363d7414f.png" alt="" style="display:block;margin:0 auto" />

<h3>The bill I didn’t expect</h3>
<p>I’ve spent months making crocket fast, and I figured that speed would show up as a smaller cloud bill. It mostly didn’t</p>
<p>At 10k req/s, the fastest framework in my benchmark saved $0. Not a little, nothing. At a projected 1M req/s, it saved $190.6k a year on the app tier against Spring, which is nothing to scoff at, but the load balancer still cost more than its whole app tier. Then I priced sending those responses to the internet: $108,349 a month for every one of the four stacks, more than the app tier, the database and the load balancer combined</p>
<p>So all that speed ended up being 3.5% of the bill. That’s not a reason to stop caring about efficiency, though, because cash isn’t the clearest thing it buys</p>
<p>Google just released the second edition of <em>Site Reliability Engineering</em> (O’Reilly, 2026), ~10 years after the first, and its announcement frames the moment in one line</p>
<blockquote>
<p><em>“The explosion of resource-intensive workloads like generative AI has changed the economics and operational requirements of infrastructure management.” (</em><a href="https://cloud.google.com/blog/products/devops-sre/sre-book-second-edition"><em>Google Cloud blog, Oct 12, 2026</em></a><em>)</em></p>
</blockquote>
<p>The book itself has a section titled “The AI Infrastructure Explosion” and a capacity planning chapter covering capacity efficiency and “Reclaiming Stranded Capacity” (<a href="https://www.oreilly.com/library/view/site-reliability-engineering/9798341607675/">table of contents, O’Reilly</a>). Every vCPU your web tier burns isn’t available for the next model, feature or failover, so efficiency isn’t a vanity metric for engineers who like fast code (guilty). It’s an input to your error budget</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/b801d7e7-2b44-48fd-bc4d-826d20b1bf86.jpg" alt="" style="display:block;margin:0 auto" />

<p>My copy of the second edition just showed up</p>
<h3>Capacity is a reliability decision</h3>
<p>This line in the capacity planning chapter actually stopped me</p>
<blockquote>
<p><em>“Capacity planning heavily parallels the concept of error budgets. Just as 100% uptime is the wrong target for reliability, provisioning for every statistical edge case is the wrong target for capacity; you must make deliberate choices based on your explicit risk tolerance.” (</em><a href="https://www.oreilly.com/library/view/site-reliability-engineering/9798341607675/ch15.html"><em>SRE 2nd ed., Ch. 15</em></a><em>)</em></p>
</blockquote>
<p>And right before it</p>
<blockquote>
<p><em>“To scale infrastructure successfully, you must balance performance, cost, and reliability — all anchored by your core business goals.” (</em><a href="https://www.oreilly.com/library/view/site-reliability-engineering/9798341607675/ch15.html"><em>SRE 2nd ed., Ch. 15</em></a><em>)</em></p>
</blockquote>
<p>The 2016 first edition already said that “paying close attention to the provisioning strategy for a service, and therefore its utilization, provides a very, very big lever on the service’s total costs,” and that “Resource use is a function of demand (load), capacity, and software efficiency” (<a href="https://sre.google/sre-book/introduction/">SRE 1st ed., Introduction</a>). What’s new is how expensive it’s become to ignore</p>
<p>Every service has three dials: traffic, headroom and compute per request. Most planning treats the third as fixed, so more reliability means more headroom and less cost means less. Efficiency is the dial that lets you have both</p>
<p>Then there’s stranded capacity: capacity you pay for that no request uses. Nobody gets paged for it, so it just sits on the bill</p>
<h3>Measured proof, framed honestly</h3>
<p>I’ve been building <a href="https://github.com/sean3z/crocket">crocket</a>, a C++26 web framework, and I measured one small CRUD API (Heroes) in four stacks on the same 4-vCPU DigitalOcean nodes against the same Postgres: crocket, Rocket (Rust, with Diesel), Java (Spring Boot 3.5 with virtual threads) and Node (Fastify 5). I picked Rocket because crocket is modeled after it, with similar developer ergonomics (axum or actix-web would likely perform better). The full benchmark is in <a href="https://medium.com/sean3z/where-the-cycles-go-c-26-rust-java-and-node-on-one-crud-api-d400dd228d21">Where the cycles go</a></p>
<p>Two measurements drive everything below:</p>
<ul>
<li><strong>CPU per request at max throughput:</strong> crocket 94 µs, Rocket 155 µs ‡, Fastify 157 µs and Spring 393 µs</li>
<li><strong>Peak memory per process:</strong> crocket 21.3 MB, Rocket 21.6 MB, Fastify 215.5 MB and Spring 471.2 MB</li>
</ul>
<p>That’s a wide spread, especially on memory</p>
<p>Now, the money. The model prices AWS EKS in us-east-1 on c6i nodes at AWS’s on-demand list prices (fetched Oct 19, 2026), including the $0.10/hour control plane, the VPC CNI’s pod-per-node IP limits and the memory Kubernetes reserves per node. Every service holds a 60% CPU target, at least two replicas and at least three nodes, one per Availability Zone. Fastify runs as single-process pods of up to 1 vCPU at 157 µs per request, because on Kubernetes you’d scale Node with more pods, not cluster mode (a 4-process cluster run used about 1.9× the CPU per request anyway)</p>
<p>Here’s the monthly app-tier bill:</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/b06b55ba-e9ad-4ffe-918c-072a8b129449.png" alt="" style="display:block;margin:0 auto" />

<p>† Projected. The highest throughput I’ve measured is 35.2k req/s, crocket on one 4-vCPU node. Every row above that linearly extrapolates measured CPU per request for all four stacks, and the charts hatch those bars</p>
<p>‡ Rocket with diesel-async’s <code>RecyclingMethod::Fast</code>, not the rocket_db_pools default, <code>Verified</code>, which sends a <code>SELECT 1</code> to Postgres every time a request checks out a connection. I measured Fast against the default back to back on the same rig and applied the ratios (app CPU per request ×0.76, Postgres CPU per request ×0.67) to the original run, since the rerun’s droplets came up on a newer Xeon. On the default pool, Rocket measured 204 µs of app CPU and 145 µs of Postgres CPU per request, and its app tier came to $694, $2,307, $5,533 and $10,994 a month at 50k, 200k, 500k and 1M req/s. That’s a pool setting, not a framework or language difference</p>
<p>In a budget review, I’d lead with that first row, where efficiency saves exactly nothing at 10k req/s. Every stack fits on the three-node minimum, so the cluster’s shape sets the bill, not the code</p>
<p>The savings only show up once a service fills nodes. At a projected 1M req/s, crocket needs 5 c6i.8xlarge nodes where Rocket needs 17 c6i.4xlarge and Spring 21 c6i.8xlarge: $60,444 a year for the app tier against $102,142 for Rocket and $251,062 for Spring. Real money, at least until you see the rest of the bill</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/6af95cd7-692c-435a-a48b-a19ae7058d45.png" alt="" style="display:block;margin:0 auto" />

<p>The fleet row tells a different story. Across 200 low-traffic microservices, memory sets the bill, not CPU. crocket and Rocket land within 8% of each other, while Spring and Node pay for JVM and V8 baselines in every one of 400 pods. To be fair though, that’s a memory lever, and a tuned JVM shrinks it a lot</p>
<h3>Look at the whole bill</h3>
<p>This is where it got humbling. At a projected 1M req/s, the app tier is a small slice of the bill for every stack, from 3.5% for crocket to 12.9% for Spring</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/20aa273f-7262-4495-942c-8e1254e5acc0.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/2e3a68d2-f68b-4a8b-b996-67e7038dad41.png" alt="" style="display:block;margin:0 auto" />

<p>‡ Fast pool recycling, as above. On the rocket_db_pools default, Rocket’s column was $10,994 app tier, $19,875 Postgres and $159,103 in total, and crocket’s saving was $13,521 (8.5%). The pool setting alone accounts for $7,590 of that: $2,482 of app tier (the same as crocket’s headroom cost below, since both are five c6i.4xlarge nodes) and $5,107 of Postgres</p>
<ul>
<li><strong>Internet egress is the elephant.</strong> A Heroes response is about 795 bytes with headers (measured with wrk2), so 1M req/s is about 2.1 PB a month. At AWS’s us-east-1 data-transfer-out tiers, which fall from $0.09 to $0.05 per GB above 150 TB, that’s $108,349 a month. It’s the same for every stack, so it changes the bill, not the savings</li>
<li><strong>Where the bytes go changes that line completely.</strong> Service-to-service traffic inside AWS pays $0. Behind CloudFront at list price, the bytes get cheaper ($74,626 a month for data and origin fetch), but an uncacheable API pays $0.01 per 10,000 HTTPS requests, another $2,628,000 a month at 1M req/s. Above 500 TB a month AWS asks you to contact them, so treat every list price here as an upper bound</li>
<li><strong>The database doesn’t fit, even when it looks like it does.</strong> At a 60% target, crocket’s Postgres load needs 125.5 vCPU, which fits the largest db.m6i instance (128 vCPU) on paper, but with 2.5 vCPU of slack a 2% traffic bump puts it past target. I priced moving the 90% of traffic that’s reads to replicas, and you’d probably shard the writes too. The other three stacks are past 128 vCPU outright</li>
<li><strong>The load balancer</strong> pushes about 3.4 TB an hour, about $19.9k a month, almost four times crocket’s whole app tier (yes, really)</li>
</ul>
<p>So, why would the framework change Postgres CPU at all? Mostly, it doesn’t. Per request, it was 75 µs for crocket, 82 µs for Spring and 89 µs for Node, within about 18% (a spread I couldn’t pin down), and all three send one prepared statement per request. Rocket’s 145 µs outlier was its pool’s <code>Verified</code> default: pg_stat_statements showed two SQL statements per request for Rocket and one for everyone else. Switching to <code>RecyclingMethod::Fast</code> cut Rocket’s Postgres CPU per request by about a third (152 to 103 µs) and its app CPU per request by 24% (187 to 143 µs), and raised its max throughput by 36% (18.2k to 24.8k req/s), as I covered in <a href="https://medium.com/sean3z/where-the-cycles-go-c-26-rust-java-and-node-on-one-crud-api-d400dd228d21">Where the cycles go</a>. That puts Rocket’s database load at about 98 µs per request, close to the other three</p>
<h3>How efficiency becomes error budget</h3>
<p>Thankfully, the mechanism is simple arithmetic. Spread a service evenly across three Availability Zones, lose one, and the survivors’ utilization becomes your target times 3/2. At a 60% CPU target that’s 90%: queues build, latency climbs and there’s no room for the retry storm that usually comes with a zonal failure. At a 40% target it’s 60%, just a normal day</p>
<p>Uneven zones make it worse. At 1M req/s and a 60% target, crocket’s 5 nodes split 2/2/1, so losing a 2-node zone multiplies load by 5/3 and takes 60% to a full 100%. Rocket’s and Node’s 17 nodes (6/6/5) land at 93%, and Spring’s 21 (7/7/7) at 90%. At 40%, crocket’s 15 smaller nodes (5/5/5) land at exactly 60% and the others at 62–63%. Fewer, bigger nodes are cheaper, but they make zone loss lumpier</p>
<p>Headroom isn’t free, though. Here’s the app tier at a projected 1M req/s at both targets:</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/106a894f-1661-4b21-b9fd-84bda274d4b4.png" alt="" style="display:block;margin:0 auto" />

<p>‡ Fast pool recycling. On the default pool, Rocket’s row was $10,994, $16,454 and $5,460</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/067bd1c8-8fbb-4e31-813d-f97a828875f9.png" alt="" style="display:block;margin:0 auto" />

<p>crocket at a 40% target costs less than any of the other three at 60%. It requests 235 vCPU where Spring at 60% requests 655, so it survives a zone loss at 60% utilization for less than the others pay to hit 90% or more. Its headroom costs $2,482 a month, 1.7% of its $145,582 whole bill. Honestly, that’s the cheapest error budget most leaders will ever be offered</p>
<h3>What efficiency buys a leader</h3>
<p>Cheaper requests give you efficiency you can spend once, in one of three ways</p>
<ol>
<li><strong>Failure headroom.</strong> Hold the bill flat and lower your utilization target, as above</li>
<li><strong>Tighter latency targets.</strong> Less CPU per request usually means less queuing. At 4k req/s in the same benchmark, p99 latency was 2.55 ms for crocket, 3.03 ms for Rocket, 3.11 ms for Spring and 8.21 ms for Node</li>
<li><strong>A lower bill.</strong> $41.7k to $190.6k a year on the app tier at a projected 1M req/s, or 3.3% to 10.2% of the whole bill</li>
</ol>
<p>So how do you pick? If the service is burning its error budget, spend on headroom, since an outage costs more than any instance. If it’s healthy but a key journey is near its latency SLO, spend on latency. Take the cash only when both are comfortably inside their objectives, and say out loud that you’re trading away margin</p>
<h3>How to bring it to a CFO</h3>
<p>The new edition’s chapter on the value of reliability describes SRE “as a business investment for the organization” and says “the measurable return on that investment can be substantial” (<a href="https://www.oreilly.com/library/view/site-reliability-engineering/9798341607675/ch02.html">SRE 2nd ed., Ch. 2</a>). A CFO won’t act on microseconds, though, so convert three things into dollars</p>
<p><strong>Outage minutes.</strong> The book puts the priority bluntly</p>
<blockquote>
<p><em>“Ensuring that a full outage of a large online shop on Cyber Monday gets mitigated after 5 instead of 15 minutes will likely be more important to the business than cutting an hour from a weekly release qualification process.” (</em><a href="https://www.oreilly.com/library/view/site-reliability-engineering/9798341607675/ch13.html"><em>SRE 2nd ed., Ch. 13</em></a><em>)</em></p>
</blockquote>
<p>Price a minute of outage for your top revenue journey, then put it next to what the headroom costs (for crocket, $2,482 a month to survive a zone loss at 60% instead of 100%) and say which failure modes it covers</p>
<p><strong>Toil hours.</strong> The 2016 first edition set a goal of keeping toil “below 50% of each SRE’s time,” reported an average of about 33% from Google’s quarterly surveys (<a href="https://sre.google/sre-book/eliminating-toil/">SRE 1st ed., Ch. 5</a>), and said that of SRE time, “no more than 25% can be spent on-call” (<a href="https://sre.google/sre-book/being-on-call/">SRE 1st ed., Ch. 11</a>). Fewer nodes and pods mean fewer things to patch, drain and page on, so multiply the hours you get back by a loaded hourly rate, conservatively</p>
<p><strong>Stranded capacity.</strong> This one’s already on the bill. In my model, crocket at 10k req/s requests 1.57 vCPU but pays for three c6i.xlarge nodes (12 vCPU), so most of that $445 a month buys nothing. Across a fleet it’s usually the cheapest money a platform team can find, and bin packing, right-sized requests and fewer minimum replicas get you there before any new framework does (even mine)</p>
<p>Put all three on one page, egress included, and “the engineers want to optimize” becomes “here’s what we’re buying, and what it’s worth”</p>
<h3>Caveats, because there’s always caveats</h3>
<ul>
<li><strong>Most of these numbers are projections.</strong> Everything from 50k req/s up assumes CPU per request stays flat as you add pods, for all four stacks. 1M req/s on cloud hardware is my goal for crocket, not a result yet</li>
<li><strong>It’s one workload.</strong> Heroes is a small read-heavy CRUD API on Postgres. Services with heavy business logic, big payloads or caches will have different ratios</li>
<li><strong>Egress depends on where your traffic goes.</strong> I priced every stack at the largest measured response (795 bytes, from wrk2) plus an assumed 150-byte request, without TLS overhead, and a CDN contract changes it a lot</li>
<li><strong>People cost dwarfs compute.</strong> Even the biggest app-tier saving here is small next to rewriting a service and re-staffing it in a new stack, and the model doesn’t count engineering time, hiring or on-call</li>
<li><strong>The fleet traffic mix is assumed.</strong> It’s illustrative, not measured</li>
<li><strong>The hardware is assumed to transfer.</strong> I measured on DigitalOcean’s 4-vCPU Xeon nodes and assumed the results hold on AWS c6i, also x86. Graviton isn’t modeled, because nothing was measured on Arm</li>
<li><strong>Spring ran untuned.</strong> Default JVM settings put its memory numbers on the high end. I tuned Rocket’s pool but not the JVM on purpose: Rocket’s fix is a one-line config change I measured, while JVM tuning wasn’t measured and mostly moves memory, not CPU per request</li>
<li><strong>Not everything is priced.</strong> Cross-AZ data transfer, storage, NAT and observability aren’t in the model, and at terabytes an hour some of them are material</li>
</ul>
<h3>Efficiency is a lever, not a rewrite</h3>
<p>None of this argues for rewriting your services. Efficiency saves nothing until a service fills nodes, and even at a projected million req/s the app tier is a small slice of the bill</p>
<p>I’d treat cost per request as a reliability input, like an SLO. Know where your load is concentrated, spend efficiency deliberately on headroom, latency or cash, and look at the whole bill before you pick the line to attack</p>
<p>The second edition says it best: “you must make deliberate choices based on your explicit risk tolerance”. Efficiency is one of those choices, and it’s the one most teams leave on the table. So, where will you spend yours?</p>
]]></content:encoded></item><item><title><![CDATA[Where the cycles go: C++26, Rust, Java and Node on one CRUD API]]></title><description><![CDATA[A Heroes CRUD shootout between crocket (C++26), Rocket (Rust), Spring Boot and Fastify, with every production feature turned on 35.2k requests per second…]]></description><link>https://rambling.hashnode.dev/where-the-cycles-go-c-26-rust-java-and-node-on-one-crud-api-d400dd228d21</link><guid isPermaLink="true">https://rambling.hashnode.dev/where-the-cycles-go-c-26-rust-java-and-node-on-one-crud-api-d400dd228d21</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Thu, 15 Oct 2026 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/634edab9-6b4f-44f9-bac2-1d3372522b15.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>A Heroes CRUD shootout between crocket (C++26), Rocket (Rust), Spring Boot and Fastify, with every production feature turned on</em></p>
<p>35.2k requests per second on one 4-vCPU box, with JSON request logs, Prometheus metrics and timeouts all on. That’s what a C++26 web service did against a real Postgres in my latest benchmark, about 2× Rocket (roughly 1.5× once Rocket’s pool health check is off), 4× Spring Boot and 5× single-process Fastify on the same hardware</p>
<p>Say “C++ for web services” and most people hear <code>malloc</code>, <code>free</code>, dangling pointers and a CVE waiting to happen. That reputation was earned, mostly by C and by C++ written like C, but modern C++ hands memory to RAII and smart pointers, and C++26’s static reflection lets a framework read plain structs and functions at compile time, the way Java or Rust frameworks use annotations or macros. It still isn’t memory-safe by construction: as the safety section concludes, it’s close with tooling, not guaranteed by the compiler</p>
<h3>Performance matters again</h3>
<p>AI inference and agent loops now share boxes with ordinary request handlers, every core-second of framework overhead is one you can’t spend on the model, and cloud bills scale with CPU time. <a href="https://blog.cloudflare.com/dns-cache-memory-optimization-1111/">Cloudflare freed about 100 TB of memory across its 1.1.1.1 fleet</a> by tightening how DNS cache entries are stored and made its DNS stack <a href="https://blog.cloudflare.com/how-we-made-our-dns-stack-3x-faster">about 3× faster</a>, and <a href="https://www.uber.com/us/en/blog/how-we-saved-70k-cores-across-30-mission-critical-services/">Uber saved around 70,000 cores</a> across mission-critical Go services just by tuning garbage collection. None of those were random, they were careful cuts to waste</p>
<p>That’s why I care about where the cycles go, not just who wins a throughput race. Headroom is a product feature, so I built the same small API four times, ran each through the same load on the same machines, and profiled where every microsecond went, including the parts where C++ came up short</p>
<h3>The setup: one API, four stacks, no shortcuts</h3>
<p>The API is a Heroes CRUD service: <code>GET /heroes</code> (first 50 by id), <code>GET</code>, <code>PUT</code> and <code>DELETE /heroes/:id</code>, and <code>POST /heroes</code>. A hero is <code>{id, name, alias, power, mentor}</code>, seeded with Barry Allen, the four Robins and 995 filler rows. All four apps pass the same 15-check conformance script, and everything is public: start at <a href="https://github.com/sean3z/heroes-shootout">github.com/sean3z/heroes-shootout</a></p>
<p>The contenders:</p>
<ul>
<li><strong>crocket</strong> (<a href="https://github.com/sean3z/crocket">github.com/sean3z/crocket</a>), my C++26 framework, built with GCC 16 on libpqxx and libpq. App: <a href="https://github.com/sean3z/heroes-crocket">sean3z/heroes-crocket</a></li>
<li><strong>Rocket 0.5 + Diesel</strong> (Rust), using <code>rocket_db_pools</code> with <code>diesel-async</code> and deadpool, the idiomatic async route in Rocket 0.5. App: <a href="https://github.com/sean3z/heroes-rocket">sean3z/heroes-rocket</a></li>
<li><strong>Spring Boot 3.5</strong> on Java 25 with <strong>virtual threads on</strong>, Tomcat, <code>JdbcClient</code> and Hikari. App: <a href="https://github.com/sean3z/heroes-spring">sean3z/heroes-spring</a></li>
<li><strong>Fastify 5</strong> on Node 24 LTS with node-postgres, named prepared statements and JSON schema response serialization. App: <a href="https://github.com/sean3z/heroes-fastify">sean3z/heroes-fastify</a></li>
</ul>
<p>Why Rocket and not axum or actix-web? crocket is named after Rocket and modeled on it, so it’s the comparison I wanted. axum or actix-web would likely land closer to crocket, so I acknowledge Rocket doesn’t holistically represent Rust’s capabilities</p>
<p>Here’s the crocket version, minus PUT and DELETE. Reflection reads the annotated functions in <code>api</code> and the <code>Hero</code> struct is the JSON schema, so there’s no route registration, no <code>new</code>, no <code>delete</code> and no manual buffer handling:</p>
<pre><code class="language-cpp">struct Hero {
  std::int64_t id;
  std::string name;
  std::string alias;
  std::string power;
  std::optional&lt;std::string&gt; mentor;
};
 
namespace api {
 
[[= http::get("/heroes")]]
auto list(Db&amp; db) -&gt; std::vector&lt;Hero&gt; {
  return db.all&lt;Hero&gt;().order_by(&amp;Hero::id).limit(50);
}
 
[[= http::get("/heroes/{id}")]]
auto get(Db&amp; db, std::int64_t id) -&gt; std::optional&lt;Hero&gt; {
  return db.find&lt;Hero&gt;(id);
}
 
[[= http::post("/heroes")]]
auto create(Db&amp; db, Json&lt;Hero&gt; body) -&gt; Created&lt;Hero&gt; {
  auto hero = db.insert(*body);
  return {hero, "/heroes/" + std::to_string(hero.id)};
}
 
// PUT and DELETE look the same
 
}  // namespace api
 
int main() {
  auto cfg = Config::from_env();
  db::Pool pool(cfg.database);
  return build(cfg)
      .manage(std::move(pool))
      .attach(Logger{})
      .attach(Metrics{})
      .mount("/", reflect_routes&lt;^^api&gt;())
      .launch();
}
</code></pre>
<h3>Production features on, for everyone</h3>
<p>A benchmark with logging off measures nothing anyone actually ships. So, every app writes one JSON log line per request, exposes Prometheus metrics at <code>/metrics</code> and enforces a 10-second timeout with its ecosystem’s normal tools: crocket’s <code>Logger</code> and <code>Metrics</code>, <code>tracing</code> and <code>rocket_prometheus</code> for Rocket, Logback ECS JSON and Micrometer for Spring, pino and prom-client for Fastify. Rocket has no built-in request timeout, so each query is wrapped in <code>tokio::time::timeout</code></p>
<p>Every app gets a 16-connection Postgres pool, but they don’t start the same way. crocket’s <code>db::Pool</code> opens all 16 before the server listens and Spring’s Hikari (<code>minimum-idle=16</code>) fills in the background, while Rocket’s and Fastify’s pools start empty: rocket_db_pools ignores <code>min_connections</code> for its deadpool and diesel backends (its docs say so), and node-postgres’s <code>min</code> only stops idle connections from being closed. That’s why the warmup fills every pool before anything is measured</p>
<h3>Hardware and method</h3>
<ul>
<li><strong>App host:</strong> DigitalOcean c-4 (4 dedicated vCPUs) in nyc1, Ubuntu 24.04, app in Docker with host networking</li>
<li><strong>Database:</strong> Postgres 16 on its own c-4, so database CPU never pollutes app CPU or the flamegraphs</li>
<li><strong>Load generator:</strong> a third c-4 running wrk2 (constant rate, corrected for coordinated omission), 4 threads, 128 keep-alive connections, HTTP/1.1</li>
<li><strong>Mix:</strong> 80% <code>GET /heroes/{id}</code>, 10% <code>GET /heroes</code>, 10% writes (5% POST, 5% PUT)</li>
<li><strong>Procedure:</strong> a 60-second warmup at 20k req/s (so JIT also gets a fair shot), a 30-second run at an unreachable rate to find the max, constant-rate steps from 25% to 115% of each app’s own max, a common 4,000 req/s step, and a saturation step at 150%</li>
<li><strong>Repetitions:</strong> 3 per load level, reporting the median</li>
</ul>
<h3>Throughput and the cost of a request</h3>
<p>On max throughput, crocket reached <strong>35.2k req/s</strong>, Rocket + Diesel <strong>17.4k</strong>, Spring Boot <strong>8.4k</strong> and Fastify <strong>6.6k</strong>, with zero errors on any max run and a tight spread across three reps: crocket 35.2–35.6k, Rocket 17.4–17.5k, Spring 8.4–8.6k, Fastify 6.1–7.0k</p>
<p>Raw req/s flatters anyone who can use more cores, so the number I trust more is CPU time per request: app CPU divided by requests served, measured from <code>/proc</code> once a second</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/013b1ee2-39e9-4e5a-9c2a-9805cd9f2fa3.png" alt="" style="display:block;margin:0 auto" />

<p>crocket spends <strong>94 µs</strong> of CPU per request, Rocket <strong>204 µs</strong>, Spring <strong>393 µs</strong> and Fastify <strong>157 µs</strong>. Per core, crocket does about 2.2× the work of Rocket and 4.2× the work of Spring</p>
<p>Fastify deserves a fair reading. It ran as a single Node process using about 1 core of the 4, which is why its max is low, and per request it’s actually cheaper than both Rocket and Spring</p>
<p>On Kubernetes you’d normally scale Fastify with more single-process pods, not cluster mode, so the single-process cost per request is the right input for cost modeling and the one I used when I priced these stacks on AWS</p>
<p>Four processes is a fair fix for this throughput test though, so I tried <code>node:cluster</code> with 4 workers. In run 1, an earlier one-rep session on different droplets, 4 workers reached 11.8k req/s against 5.8k for one process, but CPU per request went from 180 µs to 308 µs. That 5.8k sits just outside the headline range (6.1k to 7.0k req/s) because Fastify was the noisiest stack across reps, and even clustered, 11.8k is a third of crocket’s 35.2k. A back-to-back rerun on fresh droplets gave the cleaner ratio: about 1.7× the throughput for about 1.9× the CPU per request and 4.4× the memory</p>
<h3>Database CPU per request</h3>
<p>Postgres had its own droplet, so I can price each stack’s database load too: Postgres host CPU × 4 vCPU ÷ req/s at each app’s max, scaled in the last column to 1M req/s at a 60% CPU target, as in my AWS pricing. Only crocket pushed Postgres hard (<strong>66% CPU</strong>, against 17% for Spring and 15% for Fastify), so part of its ceiling may be the database, which would understate the gap</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/9379bc0c-0735-473f-8f1e-5a4f9c353c17.png" alt="" style="display:block;margin:0 auto" />

<p>crocket, Spring and Fastify land within about 18% of each other, each sending one named prepared statement per request, so the database bill is nearly framework-independent. I couldn’t pin down the rest of the spread; query-shape differences like crocket’s insert returning only the id are candidates, but they only touch 10% of requests</p>
<p>Rocket, at about twice the others, has a measured cause. rocket_db_pools uses diesel-async’s default <code>RecyclingMethod::Verified</code>, which runs a <code>SELECT 1</code> health check on every connection checkout, so in a local pg_stat_statements rerun, Rocket sent 2 statements per request to everyone else’s 1. The check takes about 1 µs inside Postgres, so the cost is the round trip, and it’s a pool default, not a property of Rust</p>
<p>So I reran Rocket with <code>RecyclingMethod::Fast</code>, back to back with the default on fresh c-4 droplets (a newer Xeon, so compare ratios, not absolutes). Fast cut Rocket’s Postgres CPU per request by about a third (152 to 103 µs), its own CPU per request by 24% (187 to 143 µs, about 23 µs of that in the kernel), and raised its max throughput by 36% (18.2k to 24.8k req/s). Scaled to this run, that’s about 155 µs per request, so against Rocket with the check off, crocket’s lead is about 1.6× per request rather than 2.2×. The headline keeps the default, because that’s what rocket_db_pools gives you out of the box</p>
<h3>Tail latency at a load everyone can handle</h3>
<p>Max throughput tells you how big the box is, but users feel latency at the load you actually run, so every app also ran at a fixed <strong>4,000 req/s</strong>, about 70% of what single-process Fastify could do</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/495ea6cf-4aa2-40b2-9a3d-d6c335136882.png" alt="" style="display:block;margin:0 auto" />

<p>p99 latency was <strong>2.55 ms</strong> for crocket, <strong>3.03 ms</strong> for Rocket, <strong>3.11 ms</strong> for Spring and <strong>8.21 ms</strong> for Fastify. The Postgres round trip dominates at this load, so three of the four land within about half a millisecond, while Fastify’s single event loop shows up in the tail (3.57 to 9.21 ms across reps)</p>
<p>What each app paid is more telling: crocket used <strong>0.49 cores</strong>, Rocket <strong>0.87</strong>, Fastify <strong>0.97</strong> and Spring <strong>1.80</strong>, so Spring with virtual threads keeps up with crocket on p99 while burning about 3.7× the CPU</p>
<p>Higher up the ramp, at 85% of each app’s own max, crocket’s p99 was 6.17 ms (about 29.6k req/s) and Rocket’s was 10.26 ms (about 14.7k req/s)</p>
<h3>Where the cycles go: flamegraphs at saturation</h3>
<p>This is the section I care about most. I profiled all four apps for 20 seconds at saturation (<code>perf</code> for crocket, Rocket and Node, async-profiler for the JVM) and bucketed every sample into handler, serialization, database driver, framework, logging, metrics, runtime and kernel. Since shares alone can mislead, the chart and table multiply each stack’s CPU per request by each bucket’s share, with “App” covering the frameworks themselves (the handler, JSON, logging, metrics, etc)</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/17366855-cfc5-43cb-acc3-c3cf07155d24.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/e7f1d0b9-8427-4b3d-aac6-2c97e12d7d75.png" alt="" style="display:block;margin:0 auto" />

<p><em>* Estimated from syscall leaf frames, because async-profiler couldn’t capture kernel stacks inside the container. /proc puts Spring’s kernel time nearer 145 µs, so its other rows are somewhat overstated. For the other three, /proc agrees with the profile within about 5 µs</em></p>
<h4>Start with crocket:</h4>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/bb57d888-1315-4609-ac8c-4f84b8d3b720.png" alt="" style="display:block;margin:0 auto" />

<ul>
<li><strong>Handler + JSON + logging: about 4.1%</strong> combined (0.2% handler, 3.0% serialization, 0.9% logging)</li>
<li><strong>Database driver (libpq/libpqxx): about 15%</strong></li>
<li><strong>Framework (h2o event loop, routing, workers): about 16%</strong></li>
<li><strong>Kernel: about 62%</strong>, mostly socket sends, <code>epoll</code> and scheduling</li>
<li><strong>Other: about 3%</strong>, mostly small libc helpers and h2o C frames the bucket script doesn’t count as framework</li>
</ul>
<p><code>/proc</code> agrees independently: 57% of crocket’s CPU at max was kernel time. That’s the punchline. <strong>crocket’s remaining cost isn’t framework tax.</strong> It’s the kernel moving bytes and libpq speaking the Postgres protocol, while my code plus logging and JSON is about 4 µs per request, so the next gains have to come from fewer syscalls: batched writes to Postgres, pipelining, maybe io_uring</p>
<h4>Spring Boot:</h4>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/dd280e7f-04ec-4367-958f-e67ff11f42ac.png" alt="" style="display:block;margin:0 auto" />

<p><strong>A</strong>bout <strong>39% framework</strong> (Tomcat, Spring MVC, filters, Hikari) and about <strong>25% JVM runtime</strong> (virtual-thread park and unpark, continuation freeze and thaw, and garbage collection). That’s roughly 150 µs of framework and 100 µs of runtime per request, more than crocket’s entire request cost</p>
<h4>Fastify:</h4>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/1f75e580-771e-4061-9a4e-357d030c9dc2.png" alt="" style="display:block;margin:0 auto" />

<p><strong>A</strong>bout <strong>20% V8 and event-loop runtime</strong>, with framework and the pg driver at about 23% each and logging at about 7%. Kernel time is only about 18%, so it spends most of its time in JavaScript and V8 before it reaches a syscall (as expected)</p>
<h4>Rocket:</h4>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/c8ebfda9-7248-4eea-b146-b2b86eac4bde.png" alt="" style="display:block;margin:0 auto" />

<p><strong>T</strong>he closest to crocket in shape, with kernel at about <strong>40%</strong>, the Tokio runtime about <strong>8%</strong>, framework about 18% and the <code>tracing</code> logging path about 5%. It’s a healthy profile, just with more layers between socket and handler, each costing a few microseconds that add up to roughly twice crocket’s per-request bill</p>
<p>A big kernel share isn’t by itself a sign of a lean framework, since less machinery means a smaller total and the same kernel work looks like a bigger slice. Rocket actually spends more time in the kernel than crocket (about 81 µs against 58 µs), nearly all of it in the network stack (about 60 µs against 34 µs), while epoll, scheduling and futex time is about 9 µs for both, which points to more socket work, not more wakeups. I didn’t count syscalls, so that’s a hint, not a finding, but Rocket’s extra pool round trip fits: turning that check off cut its kernel time by about 23 µs per request, about the size of its kernel gap to crocket</p>
<p>What really separates crocket is everything outside the kernel: framework, runtime, driver and app code come to about 33 µs per request, against about 100 µs for Rocket, 128 µs for Fastify and 250–300 µs for Spring</p>
<h3>Memory and cold start</h3>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/2a89df52-f217-454d-86e6-3ba84727e436.png" alt="" style="display:block;margin:0 auto" />

<p>Resident memory, idle and at peak under load:</p>
<ul>
<li><strong>crocket:</strong> 13 MB idle, 21 MB peak</li>
<li><strong>Rocket + Diesel:</strong> 11 MB idle, 22 MB peak</li>
<li><strong>Fastify:</strong> 87 MB idle, 216 MB peak</li>
<li><strong>Spring Boot:</strong> 225 MB idle, 471 MB peak</li>
</ul>
<p>crocket and Rocket are effectively tied and in a different weight class from the managed runtimes. Spring peaks at about 22× crocket’s memory and Fastify at about 10×</p>
<p>Cold start, from container start to the first <code>200</code> on <code>GET /heroes/1</code>:</p>
<ul>
<li><strong>Rocket:</strong> 154 ms</li>
<li><strong>crocket:</strong> 324 ms</li>
<li><strong>Fastify:</strong> 560 ms</li>
<li><strong>Spring Boot:</strong> 4.8 s</li>
</ul>
<p>Rocket wins this one cleanly, in about half crocket’s time across all three reps, mostly because of the pool: crocket opens all 16 Postgres connections before it listens (and fails fast if it can’t), while Rocket’s first <code>GET /heroes/1</code> opens just one.</p>
<p>On my own box, with Postgres local and five starts each, crocket took 141 ms to its first 200 with a 16-connection pool (130–147 ms) and 20 ms with a 1-connection pool (19–29 ms), and Rocket took 18 ms (16–20 ms). About 120 ms for 15 extra connections would cover most of the 170 ms gap on the droplets, though I haven’t timed it there</p>
<p>Spring’s 4.8 s is an untuned JVM: class data sharing (AppCDS), a CRaC checkpoint or a GraalVM native image would each change it a lot, and I didn’t try any of them</p>
<h3>Safety without the stigma</h3>
<p>None of this matters if the price is a memory-safety bug in production, so here’s what writing a C++ web service looks like in 2026</p>
<p><strong>Your code doesn’t manage memory by hand.</strong> The handlers take and return <code>Hero</code>, <code>std::optional&lt;Hero&gt;</code>, <code>std::vector&lt;Hero&gt;</code> and <code>std::string</code>, values that release their memory when they go out of scope, with shared state behind <code>std::shared_ptr</code> or <code>std::unique_ptr</code>. That’s RAII doing a garbage collector’s or borrow checker’s job, and there’s no <code>malloc</code>, <code>new</code> or <code>delete</code> anywhere in the app</p>
<p><strong>The framework fuzzes what it parses.</strong> crocket fuzzes every parser that touches untrusted input, from JSON, protobuf, query strings and routes to whole HTTP requests and HTTP/2 frame sequences against a running server. CI runs every corpus plus a short mutation burst on every push and pull request, <code>./dev fuzz</code> runs longer coverage-guided sessions with AddressSanitizer, and every crash becomes a corpus entry so it stays fixed</p>
<p><strong>The standard library can check itself.</strong> GCC’s libstdc++ hardened mode (<code>-D_GLIBCXX_ASSERTIONS</code>, or the broader <code>-fhardened</code>) bounds-checks <code>operator[]</code>, <code>front()</code>, <code>back()</code> and friends, turning many silent overflows into a clean abort. I didn’t enable it here, so its cost goes in a future follow-up to provide an honest comparison against Rust’s always-on checks</p>
<p><strong>Where Rust still has the edge.</strong> Rust’s borrow checker proves the absence of use-after-free and data races at compile time for all safe code. C++ gets close with value semantics, RAII, sanitizers, fuzzing and discipline, but “close with tooling” isn’t “guaranteed by the compiler.” A careless <code>std::string_view</code> that outlives its buffer could still compile, and crocket sits ontop C libraries (h2o and libpq) that no C++ idiom can make safer. If your team wants a compiler that refuses to build a whole class of bug, Rust may be the stronger choice, and I say that as someone whose numbers and preferences favor C++ here</p>
<p>The fair summary is that modern C++ moved the risk from “every allocation” to “a few well-known edges,” and the tooling to find those edges is good and getting better</p>
<h3>What this means for pods on Kubernetes</h3>
<p>Pods are scheduled on CPU and memory requests, and this benchmark measures both: for the same 4,000 req/s, a Spring pod needs about 3.7× crocket’s CPU and about 22× its memory, and a Fastify pod about 2× the CPU and 10× the memory</p>
<p>Memory usually limits density, because CPU can be overcommitted and memory can’t without risking the OOM killer. At around 20 MB, memory stops deciding how many replicas fit on a node, so you can run more for availability without bigger nodes</p>
<p>For scale-out, Rocket and crocket are ready in well under half a second, so an autoscaler gets capacity almost immediately during a spike, while a 4.8-second Spring start means planning headroom ahead of it</p>
<h3>Additional caveats</h3>
<p>Here’s everything that could make these numbers look better than they are:</p>
<ul>
<li><strong>The JVM ran untuned.</strong> Default Java 25 ergonomics, no heap sizing or GC choice, only <code>-XX:+PreserveFramePointer</code>. A tuned heap would shrink its memory, and AppCDS, CRaC or a native image would change the 4.8 s cold start</li>
<li><strong>One shape of workload.</strong> Read-heavy CRUD over HTTP/1.1 on 4 vCPUs. Different mixes, HTTP/2 and bigger boxes may change the ranking</li>
</ul>
<h3>Overall conclusion</h3>
<p>C++ on the web doesn’t have to be a dare anymore. On this workload, with production features on, it served twice Rocket’s traffic at less than half Rocket’s CPU per request (about 1.5× the traffic and 1.6× the work per core against Rocket with its pool health check off), in the same memory, and the profile says the remaining cost lives in the kernel and the database protocol, not the framework. That’s a much more interesting conversation than the one about <code>malloc</code></p>
<p>Everything here is reproducible. The methodology, results, charts and interactive flamegraphs are in <a href="https://github.com/sean3z/heroes-shootout">heroes-shootout</a>, and each contestant has its own repo with a Dockerfile and the same API contract: <a href="https://github.com/sean3z/heroes-crocket">heroes-crocket</a>, <a href="https://github.com/sean3z/heroes-rocket">heroes-rocket</a>, <a href="https://github.com/sean3z/heroes-spring">heroes-spring</a> and <a href="https://github.com/sean3z/heroes-fastify">heroes-fastify</a></p>
<p>If you think one of them is configured unfairly, open an issue or a PR!</p>
]]></content:encoded></item><item><title><![CDATA[Building a Rocket-style web framework with C++26 reflection]]></title><description><![CDATA[Or: I just wanted #[get("/hello")] in C++ I’ve been writing a fair bit of Rust lately and, if you’ve ever used Rocket, you know how nice it is. You write a…]]></description><link>https://rambling.hashnode.dev/building-a-rocket-style-web-framework-with-c-26-reflection-0278c8d56eaa</link><guid isPermaLink="true">https://rambling.hashnode.dev/building-a-rocket-style-web-framework-with-c-26-reflection-0278c8d56eaa</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Mon, 12 Oct 2026 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/dc8361b5-196b-490e-a00b-df1e3b49fead.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>Or: I just wanted</em> <code>#[get("/hello")]</code> <em>in C++</em></p>
<h3>The goal and background</h3>
<p>I’ve been writing a fair bit of Rust lately and, if you’ve ever used <a href="https://rocket.rs/">Rocket</a>, you know how nice it is. You write a function, slap an attribute on it, and that’s your route. No registering lambdas, no keeping a list in sync, no ceremony</p>
<p>Then I’d come back to C++ and it was back to <code>app.get("/x", []() {...})</code> lambdas or a macro of some sort. Every time</p>
<p>C++26 finally landed static reflection (P2996) and annotations (P3394). So, naturally, I wondered: could we build Rocket in C++? Not a port, just the same spirit. Simple, so let’s just do it!</p>
<p>That became <a href="https://github.com/sean3z/crocket"><strong>crocket</strong></a></p>
<h3>What it looks like</h3>
<p>Here’s the Rocket “hello world”, crocket style (straight from <code>examples/hello.cpp</code>):</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/75e2559b-0fa5-4b37-8d28-4874ba265808.png" alt="" style="display:block;margin:0 auto" />

<p>examples/hello.cpp: the whole app</p>
<pre><code class="language-cpp">#include &lt;crocket/crocket.hpp&gt;
using namespace crocket;

namespace api {

[[= http::get("/hello/{name}/{age}")]]
auto hello(std::string_view name, std::uint8_t age) -&gt; std::string {
  return std::format("Hello, {} year old named {}!", age, name);
}

[[= http::get("/")]]
auto index() -&gt; std::string { return "Try GET /hello/&lt;name&gt;/&lt;age&gt;\n"; }

}  // namespace api

int main() {
  return build(Config::from_env())
      .attach(Logger{})
      .mount("/", reflect_routes&lt;^^api&gt;())
      .launch();  // or .launch({.listen = "8080"})
}
</code></pre>
<pre><code class="language-plaintext">curl localhost:8000/hello/Rocketeer/42     -&gt; Hello, 42 year old named Rocketeer!
curl -i localhost:8000/hello/Rocketeer/400 -&gt; 404 (handler never runs)
</code></pre>
<p>That <code>400</code> doesn't fit in a <code>std::uint8_t</code>, so the request never reaches your handler. The parameter type <em>is</em> the validation</p>
<h3>So what’s actually happening?</h3>
<p>Two new pieces of C++26 do all the heavy lifting:</p>
<ul>
<li><code>[[= http::get(...)]]</code> is an annotation. It's just a normal C++ value attached to the function.</li>
<li><code>^^api</code> reflects the namespace, and <code>reflect_routes&lt;^^api&gt;()</code> walks every function inside it at compile time, reads its annotations and its parameters, and builds the route table.</li>
</ul>
<p>Forget to register a route? You can’t, there’s nothing to register. Helper functions without an annotation are simply ignored</p>
<p>All of that happens in the compiler. At runtime each route is a plain function pointer to a generated invoker. No string lookups, no RTTI, no type erasure per argument</p>
<h3>My favorite part: errors in your words</h3>
<p>Reflection can see parameter <em>names</em>, which templates never could. So crocket matches <code>{age}</code> to the parameter named <code>age</code>. Get it wrong:</p>
<pre><code class="language-cpp">[[= http::get("/hello/{name}/{age}")]]
auto hello(std::string_view name, std::uint8_t years) -&gt; std::string;
</code></pre>
<p>…and the build fails with a message naming both (<code>did you mean parameter 'years'?</code>) instead of three pages of template soup. There's a whole <code>tests/compile_fail/</code> suite that makes sure those messages stay readable</p>
<h3>JSON without the boilerplate</h3>
<p>The same trick works for bodies. Any plain struct is JSON, no derive macros or field lists:</p>
<pre><code class="language-cpp">struct NewUser {
  std::string email;                // required
  std::optional&lt;std::string&gt; name;  // may be absent or null
  int age = 0;                      // may be absent: keeps its default
};

[[= http::post("/users")]]
auto create(Json&lt;NewUser&gt; body) -&gt; Json&lt;NewUser&gt; { return body; }
</code></pre>
<p>Bad input gets a JSON Pointer to the problem (<code>field '/items/2/qty': expected integer, got string</code>)</p>
<h3>Don’t trust the internet</h3>
<p>Under the hood the wire layer is <a href="https://github.com/h2o/h2o">h2o</a> (HTTP/1.1, HTTP/2, TLS), but crocket still parses plenty of untrusted bytes itself: JSON, protobuf, query strings, routes. So every parser has a fuzz target (<code>./dev fuzz</code>), and conditional and range requests follow RFC 9110 closely (weak ETag comparison, strong-only <code>If-Range</code>, proper 416s)</p>
<p>Lesson learned the hard way: a lenient parser is just one that disagrees with the next one in line</p>
<h3>Requests per Second</h3>
<p>Okay, but is it fast? If you’ve read my <a href="https://medium.com/sean3z/rest-api-node-vs-rust-c75aa8c96343">Node vs Rust</a> post, you know I can’t help myself here. And since crocket is literally named after Rocket, it only felt right to put the two in the ring together</p>
<h3>The setup</h3>
<p>Nothing fancy, and definitely not tuned:</p>
<ul>
<li><strong>Box:</strong> one KVM virtual machine, 8 vCPUs (<code>Intel(R) Xeon(R) Processor</code>), 15 GB RAM, Linux 6.12</li>
<li><strong>crocket:</strong> <code>main</code> @ <code>2ad3f5d</code>, release build, GCC 16.2.0 with <code>-freflection</code></li>
<li><strong>Rocket:</strong> 0.5 (<code>bench/rocket</code> in the repo, same routes and same bodies), <code>cargo build --release</code> on Rust 1.99</li>
<li><strong>h2o alone:</strong> a bare h2o handler answering from constants, so we can see what crocket itself adds</li>
<li><strong>Load:</strong> <a href="https://nghttp2.org/documentation/h2load-howto.html">h2load</a> 1.64, 64 connections, 4 client threads, 30 seconds per scenario, over HTTP/1.1 and h2c (HTTP/2 without TLS)</li>
</ul>
<p>The scenarios:</p>
<table>
<thead>
<tr>
<th>Scenario</th>
<th>Request</th>
<th>What it measures</th>
</tr>
</thead>
<tbody><tr>
<td>plaintext</td>
<td>GET /plaintext</td>
<td>The pipeline with the least work</td>
</tr>
<tr>
<td>json</td>
<td>GET /json</td>
<td>Encoding a small struct</td>
</tr>
<tr>
<td>orders</td>
<td>POST /orders</td>
<td>Decoding and encoding a 1 KB order</td>
</tr>
<tr>
<td>router</td>
<td>GET /api/v39/users/7/orders/9</td>
<td>A route matched last out of ~200</td>
</tr>
</tbody></table>
<p>I knew I’d be running this benchmark often, so it’s all baked into the repo, you don’t have to take my word for it:</p>
<pre><code class="language-plaintext">./dev bench --vs-rocket --vs-h2o --duration 30 load plaintext json orders router
</code></pre>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/55804b86-e529-4b26-bcc8-fdd883ef4609.png" alt="" style="display:block;margin:0 auto" />

<p>The raw ./dev bench output: crocket vs Rocket 0.5, and crocket vs bare h2o</p>
<h3>crocket vs Rocket</h3>
<p>The results, honestly, surprised me a bit!</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/8bc3a8c9-2034-4648-a623-ce8c016e06db.png" alt="" style="display:block;margin:0 auto" />

<p>Requests per second over HTTP/1.1, crocket vs Rocket 0.5</p>
<table>
<thead>
<tr>
<th align="right">HTTP/1.1</th>
<th>crocket req/s</th>
<th>Rocket req/s</th>
<th>ratio</th>
<th>p50 ms (c / R)</th>
<th>p99 ms (c / R)</th>
<th>CPU µs/req (c / R)</th>
</tr>
</thead>
<tbody><tr>
<td align="right">plaintext</td>
<td>404,401</td>
<td>204,897</td>
<td>1.97x</td>
<td>0.13 / 0.26</td>
<td>0.72 / 1.0</td>
<td>9.69 / 18.38</td>
</tr>
<tr>
<td align="right">json</td>
<td>400,811</td>
<td>197,167</td>
<td>2.03x</td>
<td>0.12 / 0.27</td>
<td>0.78 / 1.07</td>
<td>9.89 / 18.71</td>
</tr>
<tr>
<td align="right">orders</td>
<td>219,322</td>
<td>172,513</td>
<td>1.27x</td>
<td>0.24 / 0.31</td>
<td>1.06 / 1.26</td>
<td>24.02 / 26.24</td>
</tr>
<tr>
<td align="right">router</td>
<td>372,110</td>
<td>187,271</td>
<td>1.99x</td>
<td>0.12 / 0.28</td>
<td>1.05 / 1.20</td>
<td>10.33 / 21.29</td>
</tr>
</tbody></table>
<p>On the simple routes crocket served right around <strong>2x the requests per second</strong>, at about half the CPU per request. The <code>orders</code> scenario is where it gets closer (1.27x): once both frameworks have to actually parse and build a 1 KB JSON body, that work dominates and the gap shrinks</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/2ea5cc0b-b199-4301-9973-66f711a075c9.png" alt="" style="display:block;margin:0 auto" />

<p>p50 latency, HTTP/1.1</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/644b2c86-68ad-44fd-9cc5-c19ea4fb504e.png" alt="" style="display:block;margin:0 auto" />

<p>p99 latency, HTTP/1.1</p>
<p>Latency tells the same story: p50 sits around 0.12 ms for crocket vs 0.26–0.31 ms for Rocket, and p99 stays under ~1 ms for the simple routes</p>
<p><em>Sidenote: Rocket 0.5 only serves HTTP/2 over TLS, so the head-to-head is HTTP/1.1 only</em></p>
<h3>The old-school way (wrk)</h3>
<p>For old times’ sake, I also ran the exact same command from my Node vs Rust post. One minute of <code>wrk</code> defaults (2 threads, 10 connections) against <code>/plaintext</code>:</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/0091c0ec-a0d5-4106-982f-abe86bd0fd65.png" alt="" style="display:block;margin:0 auto" />

<p>wrk -d1m against crocket and Rocket, plus memory use</p>
<ul>
<li><strong>crocket:</strong> 254,413 req/s</li>
<li><strong>Rocket:</strong> 135,904 req/s</li>
</ul>
<p>Same ballpark ratio (~1.9x). And for memory: crocket idled at about <strong>7.5 MB</strong> RSS (10.7 MB after the run) while Rocket idled at about <strong>6 MB</strong> (7.4 MB after). So Rocket still wins the “how little RAM can you sit on” category</p>
<p>Fair’s fair 🤷‍♂️</p>
<h3>HTTP/2 and what crocket actually costs</h3>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/0fef97ac-aa05-485e-ab76-52ecaa060869.png" alt="" style="display:block;margin:0 auto" />

<p>crocket over HTTP/1.1 vs h2c</p>
<p>Over h2c, crocket pushed <strong>660,542 req/s</strong> on plaintext and 576,910 on json (vs ~400k over HTTP/1.1)</p>
<p>The more interesting number for me was comparing against bare h2o, which is crocket’s wire layer. That’s the “how much does all this reflection magic cost at runtime?” question:</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/727644f8-955d-4e45-a54c-0cc2b4114ef8.png" alt="" style="display:block;margin:0 auto" />

<p>Server CPU per request: crocket, Rocket and bare h2o</p>
<pre><code class="language-plaintext">CPU µs per request | crocket | bare h2o | crocket adds
-------------------+---------+----------+-------------
plaintext h1       | 9.69    | 7.07     | +2.62
json h1            | 9.89    | 7.00     | +2.89
router h1          | 10.33   | 6.90     | +3.43
orders h1          | 24.02   | 7.33     | +16.69
plaintext h2c      | 7.22    | 1.47     | +5.75
</code></pre>
<p>So routing ~200 routes, extracting typed params and adding the default headers (request id, ETag, <code>Shield</code>'s security headers) cost <strong>2.6–3.4 µs per request</strong> over raw h2o on HTTP/1.1. That’s small in absolute terms, but it isn’t free: h2o itself spends 6.9–7.1 µs on those requests, so crocket adds about 37–50% on top of its own wire layer. The h2o handler answers from constants though, so <code>orders</code> there isn't really parsing anything; that +16.69 µs is mostly the actual JSON work. Over h2c the gap is bigger, and h2o's h2c numbers were limited by the load generator (h2load was ~100% busy), so there's clearly some room to dig into</p>
<p>For the record, here’s what was attached during the bench. crocket ran with only its defaults: Shield (attached automatically), an x-request-id and an ETag on every 200, and no Logger or Metrics (bench/server.cpp only attaches those when you ask). Rocket ran with its defaults too, and Rocket 0.5 also attaches its own Shield automatically. The header work wasn’t identical, though. Over plain HTTP crocket’s Shield sends four headers (nosniff, x-frame-options: DENY, a CSP and referrer-policy), while Rocket’s sends three (nosniff, X-Frame-Options: SAMEORIGIN and a Permissions-Policy). Rocket also doesn’t add a request id or hash the body for an ETag. So if anything, crocket was doing a bit more per response, not less</p>
<p>The caveats</p>
<p>Let’s be honest, benchmarks are mostly lies we tell ourselves 😅</p>
<ul>
<li>This is a <strong>single VM</strong>, and the load generator ran on the <strong>same 8 vCPUs</strong> as the server. Nothing was tuned: no CPU pinning, no kernel tweaks</li>
<li>One run per scenario. Treat differences of a few percent as noise</li>
<li>Same-box load generation and a single run is the weak version of this test. For the rigorous one, with a separate load generator, a real Postgres, three reps per load level and every production feature on, see <a href="https://medium.com/sean3z/where-the-cycles-go-c-26-rust-java-and-node-on-one-crud-api-d400dd228d21">Where the cycles go</a></li>
<li>For the bare h2o runs, h2load itself was the bottleneck (97–100% busy), so those req/s are the client’s limit. The CPU-per-request column is the fairer comparison there</li>
<li>These are “hello world”-ish handlers. Real apps with databases will look very different</li>
</ul>
<p>Still, I’m pretty happy that compile-time reflection comes with such a small runtime bill: about 3 µs a request over the bare wire layer, and still about half Rocket’s CPU per request on the simple routes. I think crocket wins this category… at least for now!</p>
<h3>Production first</h3>
<p>Here’s the thing about my side projects: they usually work great right up until somebody actually runs them prod. So this time I wanted the boring stuff in the box from day one, not “left as an exercise for the reader” (aka me, at 2am, during an outage)</p>
<p>Rocket fans will feel at home: the middleware is called <em>fairings</em>, with the same hooks (<code>on_ignite</code>, <code>on_request</code>, <code>on_response</code>, <code>on_shutdown</code>), except they're just plain structs. The standard ones live in <code>include/crocket/fairings.hpp</code>:</p>
<ul>
<li><code>Logger</code>: one structured JSON line per request with the request id, trace id, the <em>route template</em> (not the raw path), the handler name, status, duration, bytes and protocol. Lines are written by a background thread, so a slow log shipper doesn't slow requests down, and you can set level, sampling, redaction and a custom sink through <code>Config::log</code></li>
<li><code>Metrics</code>: Prometheus at <code>GET /metrics</code>, also labeled by route template, so <code>/users/1</code> and <code>/users/2</code> don't blow up your cardinality</li>
<li><code>Shield</code>: security headers on every response (<code>nosniff</code>, <code>x-frame-options: DENY</code>, a locked-down CSP, <code>no-referrer</code>, HSTS on https). It's attached <em>by default</em>, because nobody remembers to add it. <code>Shield::none()</code> turns it off if you really must</li>
<li><code>Cors</code>: defaults to deny. You opt in with <code>Cors::allow_origins({...})</code></li>
</ul>
<p>Then there’s a bunch you get without asking: <code>GET /healthz</code> and <code>GET /readyz</code> (a managed <code>Pool</code> drives readiness), an <code>x-request-id</code> on every response, graceful shutdown on SIGINT/SIGTERM (stop accepting, drain in-flight requests, run <code>on_shutdown</code>, then destroy state), and TLS certificates that reload on SIGHUP or when the files change, no restart needed</p>
<p>Limits are just config, and every one of them has a real error code instead of a mystery hang:</p>
<pre><code class="language-cpp">// README.md, "Launching"
Config cfg = Config::from_env();         // every CROCKET_* variable, then your code
cfg.timeouts.request      = 10s;         // 504 deadline.exceeded
cfg.limits.max_body_bytes = 1 &lt;&lt; 20;     // 413 body.too_large
cfg.limits.max_in_flight  = 1024;        // 503 server.busy
cfg.timeouts.drain        = 5s;          // graceful shutdown budget

return crocket::build(cfg)
    .manage(std::move(pool))
    .attach(Logger{})
    .attach(Metrics{})
    .mount("/api", reflect_routes&lt;^^api&gt;())
    .launch({.listen = "8443", .tls_cert = "cert.pem", .tls_key = "key.pem"});   // h2 via ALPN
</code></pre>
<p>And here’s what one request to <code>examples/serve.cpp</code> actually logs:</p>
<pre><code class="language-javascript">{"ts":"2026-10-12T17:45:59.495Z","level":"info","msg":"request","request_id":"c3c31bc77b0230ff5c5597d7530b118a","method":"GET","route":"/openapi.json","status":200,"code":"","duration_ms":0.056,"bytes_in":0,"bytes_out":7193,"proto":"http/1.1","client":"127.0.0.1","user_agent":"curl/8.14.1"}
</code></pre>
<p>…and the matching scrape from <code>/metrics</code>:</p>
<pre><code class="language-plaintext"># TYPE crocket_http_requests_total counter
crocket_http_requests_total{method="GET",route="/healthz",status="200"} 1
crocket_http_requests_total{method="GET",route="/openapi.json",status="200"} 1
</code></pre>
<p>Handlers also get a <code>Deadline</code> parameter, so a slow database call can notice the request is already dead and bail out. There are worker gauges like <code>crocket_workers_stuck</code> for the ones that don't. Is it Kubernetes-ready? I'd say it's at least Kubernetes-<em>polite</em></p>
<h3>gRPC and OpenAPI for free (thanks, reflection)</h3>
<p>This is where reflection really pays off. I’ve maintained enough <code>.proto</code> files and hand-written Swagger YAML to know how it goes: the docs say one thing, the code does another, and the codegen step breaks the build every other Tuesday</p>
<p>In crocket, <strong>the C++ declarations are the schema.</strong> A gRPC method is just an annotated function, and its messages are plain structs (from <code>examples/grpc.cpp</code>):</p>
<pre><code class="language-cpp">struct HelloRequest {
  std::string name;                                    // field 1
  std::optional&lt;std::string&gt; title;                    // field 2
  [[= proto::field(4)]] std::vector&lt;std::string&gt; tags;  // field 4 (3 was retired)
  Mood mood = Mood::calm;                              // field 5
};

namespace greeter {
[[= grpc::rpc]]
auto say_hello(HelloRequest req, State&lt;Counter&gt; counter) -&gt; Result&lt;HelloReply&gt;;
}

// main():
//   .mount("helloworld", reflect_routes&lt;^^greeter&gt;(), Mode::Grpc)
</code></pre>
<p>There’s no <code>protoc</code> and no generated code. Your other-language clients still need a <code>.proto</code>, though, so crocket writes one out from the same declarations. This is the real output of <code>./build/crocket_grpc --proto</code>:</p>
<pre><code class="language-cpp">// Generated by crocket from C++ declarations.
syntax = "proto3";
package helloworld;
import "google/protobuf/empty.proto";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
  rpc Whoami (google.protobuf.Empty) returns (HelloReply);
  rpc Tenant (google.protobuf.Empty) returns (HelloReply);
}

message HelloRequest {
  string name = 1;
  optional string title = 2;
  repeated string tags = 4;
  Mood mood = 5;
}

enum Mood {
  MOOD_CALM = 0;
  MOOD_HAPPY = 1;
  MOOD_GRUMPY = 2;
}
</code></pre>
<p>The same reflection does the bookkeeping too. <code>say_hello</code> becomes <code>SayHello</code>, enum values get their proto3 prefix, an <code>ApiError</code> maps to the right gRPC status, and <code>Header&lt;"x-tenant"&gt;</code> reads gRPC metadata. And because it all happens at compile time, mistakes are <em>compile errors</em>. Pin two members to the same field number and GCC tells you:</p>
<pre><code class="language-plaintext">error: static assertion failed: crocket: proto message Widget: members 'size' and 'colour'
both have field number 2; pin one with [[= proto::field(n)]]
</code></pre>
<p>OpenAPI works the same way. One line:</p>
<pre><code class="language-cpp">app.attach(OpenApi{{.title = "Orders", .version = "1.4.0", .docs = "/docs"}});
</code></pre>
<p>…and <code>GET /openapi.json</code> serves an OpenAPI 3.1 document built from the handlers themselves: path captures and their types, <code>Query&lt;T&gt;</code>, <code>Header&lt;...&gt;</code>, <code>Json&lt;T&gt;</code> bodies, <code>Auth</code> as a bearer requirement, and the response types. <code>/docs</code> gives you Swagger UI. Take this handler from <code>examples/serve.cpp</code>:</p>
<pre><code class="language-cpp">struct NewUser { std::string email; std::optional&lt;std::string&gt; name; };

[[= http::post("/users")]]
auto create(Json&lt;NewUser&gt; body, Auth auth, State&lt;DbPool&gt; db, Deadline d) -&gt; Result&lt;Created&lt;User&gt;, ApiError&gt;;
</code></pre>
<p>Here’s what the running server actually serves for it (trimmed):</p>
<pre><code class="language-javascript">"NewUser": {
  "type": "object",
  "properties": {
    "email": { "type": "string" },
    "name":  { "type": ["string", "null"] }
  },
  "required": ["email"]
}
...
"/api/users": { "post": { "operationId": "api.create", "summary": "Create",
                          "security": [{ "bearer": [] }] } }
</code></pre>
<p><code>email</code> is required because it's not optional and has no default. That's the same rule <code>Json&lt;T&gt;</code> uses when it parses the request, so the docs and the parser literally can't disagree. Need it at build time, say to check it into the repo or feed a client generator? <code>crocket::openapi_document(app, {...})</code> returns the document as a string</p>
<p>That’s my favorite part: one source of truth, and the compiler checks it for you</p>
<p>A couple of honest caveats: gRPC is <strong>unary only</strong> for now (no streaming), it needs HTTP/2 (TLS with ALPN, or <code>server.h2_prior_knowledge</code> / <code>CROCKET_H2_PRIOR_KNOWLEDGE=1</code> for plaintext), and gRPC methods are left out of the OpenAPI doc since their contract is the <code>.proto</code></p>
<h3>The catch</h3>
<p>Let’s be honest, there’s always a catch 😅</p>
<ul>
<li>You need <strong>GCC 16.2</strong> with <code>-freflection</code>. Ubuntu's <code>g++-16</code> package is a pre-release snapshot that can't build it, so <code>./dev gcc</code> builds GCC from source (go grab a coffee... or two)</li>
<li>Clang isn’t supported yet. Once other compilers catch up, crocket will follow</li>
</ul>
<h3>Try it</h3>
<pre><code class="language-plaintext">git clone https://github.com/sean3z/crocket &amp;&amp; cd crocket
./dev setup &amp;&amp; ./dev gcc &amp;&amp; ./dev check
./build/crocket_hello
</code></pre>
<p>Don’t want to build GCC 16.2 yourself? (fair, it takes ages 😅) You can poke at the reflection bits right in your browser on <a href="https://godbolt.org/z/Gdes8Kbdq">Compiler Explorer</a>, or run the hello example with Docker:</p>
<pre><code class="language-plaintext">docker run -p 8000:8000 ghcr.io/sean3z/crocket-hello
curl localhost:8000/hello/Rocketeer/42
</code></pre>
<p>I’d love to hear what you’d build with it. Come say hi in <a href="https://github.com/sean3z/crocket/discussions/19">GitHub Discussions</a>, and if you want to pitch in, there are a few issues tagged <code>good first issue</code></p>
<p>Happy hacking!</p>
]]></content:encoded></item><item><title><![CDATA[Rust, I just wanted to spawn a Tank!]]></title><description><![CDATA[Bradley APC in Rust (via Rustified) A few friends and I recently started playing Rust and it can certainly be a lot of fun. So long as you can manage to…]]></description><link>https://rambling.hashnode.dev/rust-i-just-wanted-to-spawn-a-tank-447a28ee37c0</link><guid isPermaLink="true">https://rambling.hashnode.dev/rust-i-just-wanted-to-spawn-a-tank-447a28ee37c0</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 12 Mar 2023 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/2b02a48c-9b4e-46c7-b316-5cfca36ffae6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Bradley APC in Rust (via Rustified)</p>
<h3>The goal and background</h3>
<p>A few friends and I recently started playing <a href="https://rust.facepunch.com/">Rust</a> and it can certainly be a lot of fun. So long as you can manage to stay alive..</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/ab4fd0df-e365-465b-93db-2e4867c345a9.gif" alt="" style="display:block;margin:0 auto" />

<p>As we got further into the game, one friend decided to host a server — which has been great for learning more about the game! To add to the fun, he installed the <a href="https://umod.org/plugins/guarded-crate">Guarded Crate</a> plugin by <a href="https://umod.org/user/Bazz3l">Bazz3l</a>.</p>
<p>The plugin functionality is straight forward: it randomly spawns events throughout the map with <a href="https://rustlabs.com/entity/locked-crate">Locked Crates</a>. If you defeat the Guards (“Scientists”) protecting the Crate, you get the sweet, sweet loot locked inside.</p>
<p>Never satisfied, we wondered if it’d be possible to extend it with the following functionality:</p>
<ul>
<li>Spawn BradleyAPC Tank to help protect the Crate (because why not?)</li>
</ul>
<p>And while we’re there, a couple minor tweaks:</p>
<ul>
<li>Event to spawn at Player’s current location (instead of only random)</li>
<li>Add Guard diversity (so they’re no longer all the same)</li>
</ul>
<h3>Simple, so let’s just modify the plugin!</h3>
<p>Now that we have our scope defined, I quickly realized I <em>know nothing</em> about the following:</p>
<ul>
<li>Rust plugin development</li>
<li>Unity</li>
<li>C#</li>
</ul>
<p>Apparently, all important things when authoring or modifying Rust plugins.</p>
<h3>Okay, well let’s start with the documentation!</h3>
<blockquote>
<p>Good luck. Rust plugin documentation is incredibly sparse!<br /> — Some Random Developer</p>
</blockquote>
<p>Seriously, this is probably an understatement. Most forums tell you to, “just look at other plugins”. While that certainly never hurts, here’s a few references that helped me along the way:</p>
<ul>
<li><a href="https://umod.org/documentation/games/rust">https://umod.org/documentation/games/rust</a></li>
<li><a href="https://medium.com/@thethingtracks/simple-rust-plugin-template-a0f405da8f64">https://medium.com/@thethingtracks/simple-rust-plugin-template-a0f405da8f64</a></li>
<li><a href="https://www.youtube.com/watch?v=vpv4T_WG9hU">https://www.youtube.com/watch?v=vpv4T_WG9hU</a></li>
<li><a href="https://umod.org/community/rust/31489-guide-to-create-a-plugin">https://umod.org/community/rust/31489-guide-to-create-a-plugin</a></li>
</ul>
<h3>Decompiling Rust Server DLLs</h3>
<p>If you’re starting out and curious about methods, capabilities, and default behaviors, you’ll need to decompile Assembly-CSharp.dll (one of Rust’s main server libraries)</p>
<p><em>You can get this DLL by completing the first step in</em> <a href="https://wiki.facepunch.com/rust/Creating-a-server"><em>Create a Rust server</em></a><em>. You don’t need to run the server, just allow it to download the most recent DLL</em></p>
<p>It may sound like a daunting step (one that I put off WAY longer than I should have) but, incredibly insightful. And thankfully there’s many tools that make this easy.</p>
<p><a href="https://www.telerik.com/products/decompiler.aspx">Telerik’s JustDecompile</a> is a great free tool (despite needing to sign up) and made reviewing Rust internals a breeze.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/5cb6e755-fc8e-4718-a5e4-e7b1f372035b.png" alt="" style="display:block;margin:0 auto" />

<p>This step helped me feel much more prepared to dive into existing Plugin code, so let’s move on to the fun!</p>
<h3>Allow Event to spawn at Player location</h3>
<p>The plugin already has the ability to spawn at random locations, I figured it couldn’t be too difficult to spawn on the player instead and could serve as a good entry point into the existing Plugin code.</p>
<p>Thankfully, it turned out to be easier than I thought:</p>
<pre><code class="language-csharp">private Vector3 GetPlayerPosition(IPlayer player)
{
  BasePlayer _player = player.Object as BasePlayer;
  return _player.transform.position;
}
</code></pre>
<p>I simply created and basically referenced this method, wherever FindRandomPosition() was found</p>
<p><em>Sidenote: I don’t yet understand the relationship between IPlayer and BasePlayer. Almost everything extends from a “Base”-related class, so the type coercion may not be necessary. I also don’t yet fully understand Unity’s</em> <a href="https://docs.unity3d.com/ScriptReference/Vector3.html"><em>Vector3</em></a> <em>outside of it being a representation of space or points on the map.</em></p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/74239a4f-6780-4d33-8fd7-bcbb21078a52.gif" alt="" style="display:block;margin:0 auto" />

<p>Success!! The event spawned on me instead of a random location!</p>
<p><em>Yup, lesson learned... enable</em> <a href="https://www.corrosionhour.com/rust-god-mode-command/"><em>God mode</em></a> <em>when testing 🤦‍♂️</em></p>
<h3>Adding Guard diversity</h3>
<p>After reviewing a few other plugins, I was able to find the prefab locations of the other Scientists.</p>
<ul>
<li><a href="https://www.corrosionhour.com/rust-prefab-list/"><em>Check here for a comprehensive prefab list</em></a></li>
</ul>
<p>I slung them into an array, then learned about Unity’s <a href="https://docs.unity3d.com/ScriptReference/Random.Range.html">Random.Range()</a>, and used this inside the existing NPC spawn method instead. Super Easy!</p>
<pre><code class="language-csharp">string[] NPC_PREFABS = {
  "assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_roam.prefab",
  "assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_heavy.prefab",
  "assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_oilrig.prefab",
  "assets/rust.ai/agents/npcplayer/humannpc/scientist/scientistnpc_patrol.prefab"
};

var prefab = NPC_PREFABS[Random.Range(0, NPC_PREFABS.Length - 1)];
var npc = (ScientistNPC)GameManager.server.CreateEntity(prefab, position, rotation);
</code></pre>
<p>To my delight, it cycled through the Scientist prefabs</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/952140f0-e71d-4372-9dfc-c410b33b91d8.gif" alt="" style="display:block;margin:0 auto" />

<p>Woot! They’re different now!</p>
<h3>Spawn BradleyAPC Tank</h3>
<p>Alright, different Guard prefabs was easy enough. Let’s try the Tank!</p>
<p>I added the following code to the NPC spawn method</p>
<pre><code class="language-csharp">string BRADLEY_PREFAB = "assets/prefabs/npc/m2bradley/bradleyapc.prefab";

var apc = (BradleyAPC)GameManager.server.CreateEntity(BRADLEY_PREFAB, position, rotation);
apc.enableSaving = false;
apc.Spawn();
</code></pre>
<p>Annnd…</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/5338be44-214a-40ef-a5a2-857c9b5b80b4.gif" alt="" style="display:block;margin:0 auto" />

<p>Tank is running away, shooting his friends and doesn’t care about me... fail-tastic!</p>
<p>So apparently…the BradleyAPC has a mind of its own.</p>
<p>It may be hard to tell but, it’s opening fire on its NPC friends and trying to complete its predefined path 🤷‍♂️</p>
<p>This is where decompiling Assembly-CSharp.dll was incredibly helpful. I was able to understand which methods were available to control the APC (unfortunately, not many).</p>
<pre><code class="language-csharp">apc.targetList.Clear();
apc.ClearPath();
</code></pre>
<p>The two above though, help prevent the Tank from taking a casual stroll wherever it decides. It also removes all immediate targets. Now the end result is more inline with what we’d expect!</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/3553f9ab-58cb-4155-9b58-9748ed21f3d4.gif" alt="" style="display:block;margin:0 auto" />

<p>Diversity, at my location, and a Tank! Success!!</p>
<p>There’s probably far more sophisticated ways to control Tank NPC targets as I certainly don’t purport to be an expert but, this was an incredibly fun way to learn the Rust plugin ecosystem and complexities to “just” spawning any NPC!</p>
<p>Check out my (crude) changes to the GuardedCrate plugin below!</p>
<ul>
<li><a href="https://github.com/sean3z/GuardedCrate-Rust/compare/main?expand=1&amp;w=1"><em>https://github.com/sean3z/GuardedCrate-Rust</em></a></li>
</ul>
<p>Happy Rust’ing!</p>
]]></content:encoded></item><item><title><![CDATA[Building a CHIP-8 emulator with Rust (Part 1)]]></title><description><![CDATA[Writing an emulator has been on my developer “TODO list” for quite some time. Ever since playing an NES emulator for the first time, I’ve always been…]]></description><link>https://rambling.hashnode.dev/building-a-chip-8-interpreter-with-rust-part-1-9c3707ddbb35</link><guid isPermaLink="true">https://rambling.hashnode.dev/building-a-chip-8-interpreter-with-rust-part-1-9c3707ddbb35</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Tue, 22 Nov 2022 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/81b82730-e494-44f7-852b-ca4eccc24100.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Writing an emulator has been on my developer “TODO list” for quite some time. Ever since playing an NES emulator for the first time, I’ve always been curious as to how they work.</p>
<p><em>Check out the complete project:</em> <a href="https://github.com/sean3z/chip8-emulator-rust"><em>https://github.com/sean3z/chip8-emulator-rust</em></a></p>
<p>Thankfully, there’s a ton of documentation these days that outline exactly how Emulators work. So I’ve challenged myself to develop one in Rust; first: to better understand Rust and second: to finally check this off my bucket list.</p>
<p>The caveat here, there are millions of articles that cover this very subject — and likely much better than I’m capable. Being new to both Rust and the world of emulation, this post (and the subsequent thereafter) is aimed solely to share my experiences along the way.</p>
<p>Anyway, after a bit of research, CHIP-8 was recommended as a good starting point for those interested in getting into this space, largely due to the small number of <a href="https://en.wikipedia.org/wiki/Opcode">opcodes</a> that need to be implemented (35 to be exact).</p>
<h4>About Chip-8</h4>
<p>From what I’ve learned, Chip-8 is a small interpreted language created in the late 1970’s. Almost twenty years after it was created, Chip-8 interpreters became popular on graphing calculators, enabling users to play various games —with some major games being <a href="https://en.wikipedia.org/wiki/Backporting">backported</a>: Pong, Space Invaders, Tetris, and Pac-Man.</p>
<p>The interpreter took 512 bytes of memory, on systems that had between 1 and 4K of RAM, with a monochrome display resolution of 64x32.</p>
<h4>Getting Started</h4>
<p>So I began by reading <a href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#0.0">Cowgod’s Chip-8 Technical Reference</a>, which will be quoted a few times throughout this post. Ultimately, there are 4 parts to any basic system:</p>
<ul>
<li>Input (Keyboard)</li>
<li>Output (Display, Sound)</li>
<li>CPU</li>
<li>Memory</li>
</ul>
<p>More advanced gaming systems, like the NES, have <a href="https://wiki.nesdev.com/w/index.php/NES_reference_guide">additional components</a> but, this is all we’ll need to get our Chip-8 interpreter running.</p>
<h4>Putting a System in place</h4>
<pre><code class="language-plaintext">[sean@lappy486:~/] $ cargo new chip8-emulator-rust --bin
     Created binary (application) `chip8-emulator-rust` project
</code></pre>
<p>At a high level, my initial thought process is to have a <code>CPU</code> that can manage all the other ancillary components <code>Memory</code>, <code>Keypad</code>, and <code>Display</code>.</p>
<p><em>Sidenote: I didn’t realize</em> <code>Sound</code> <em>would be so Rust difficult but, more on that later</em></p>
<p>As a result, our <code>main</code> application would simply initialize (startup) the CPU, load a game, and then use an infinite loop to complete various cycles.</p>
<pre><code class="language-rust">use cpu::Cpu;

mod cpu;
mod keypad;
mod display;

fn main() {
    let mut cpu = Cpu::new();

    cpu.load_game("/home/sean/www/chip8-emulator-rust/roms/pong");

    'main : loop {
        cpu.emulate_cycle();
    }
}
</code></pre>
<h4>Starting our CPU component</h4>
<p>This is arguably where most of the core logic will live but, to get us started we’re going to hit the basic functionality then revisit.</p>
<p>Aside from Memory, Input &amp; Display, the primary pieces for now:</p>
<ul>
<li><em>Program Counter</em>: used to store the current executing memory address. This starts at 0x200 (512) as that’s where applications begin</li>
<li><em>Stack Storage</em>: used as a convenience method for history purposes</li>
<li><em>Stack Pointer</em>: the topmost level of the storage stack</li>
<li><em>Opcode</em>: the opcode being processed by the current cycle</li>
<li><em>Registers</em>: Chip-8 has 16 general purpose 8-bit registers, usually referred to as V<em>x</em>, where <em>x</em> is a hexadecimal digit (0 through F). There is also a 16-bit register called I. This register is generally used to store memory addresses, so only the lowest (rightmost) 12 bits are usually used. [1]</li>
</ul>
<pre><code class="language-rust">use rand;
use std::fs::File;

use display::Display;
use keypad::Keypad;

pub struct Cpu {
    program: usize, // program counter starts at 512 bytes
    opcode: u16, // current opcode
    stack: [u16; 16], // stack storage
    stack_pointer: usize, // stack pointer

    v: [u8; 16], // cpu registers (V0 through Ee)
    i: usize, // index register

    memory: [u8; 4096], // system memory
    pub keypad: Keypad, // intercept keyboard calls
    pub display: Display, // visualize on screen
}

impl Cpu {
    pub fn new() -&gt; Cpu {
        Cpu {
            program: 0x200,
            opcode: 0,
            stack: [0; 16],
            stack_pointer: 0,

            v: [0; 16],
            i: 0x200,

            memory: [0; 4096],
            keypad: Keypad::new(),
            display: Display::new(),
        }
    }
}
</code></pre>
<h4>Loading ROMs into memory</h4>
<p>Now that we have our memory setup, we should be able to load just about any <a href="http://www.zophar.net/pdroms/chip8/chip-8-games-pack.html">Chip-8 ROM</a>. Remember, applications are loaded starting at 0x200 (512) since 0x000 through 0x1FF (511) are allocated to the interpreter.</p>
<p>We’ll add our <code>cpu.load_game()</code> method referenced in <code>main</code> to accept a parameter containing the full path to a Chip-8 ROM.</p>
<pre><code class="language-rust"> pub fn load_game(&amp;mut self, game: &amp;str) {
    // attempt to load supplied ROM
    let mut reader = File::open(game).expect("Unable to locate ROM");
    let mut buffer = Vec::new();
    reader.read_to_end(&amp;mut buffer).expect("Unable to read ROM data");

    // load ROM into memory (AFTER system reserved memory)
    for i in 0..buffer.len() {
        self.memory[i + self.program] = buffer[i];
    };
}
</code></pre>
<h4>Loading Sprites into memory</h4>
<p>There’s something else we can go ahead and load into memory as well. Similar to a <a href="https://css-tricks.com/css-sprites/">CSS sprite</a>, Chip-8 uses a group of pre-determined bytes to represent desired numbers and letters (0–9 and A-F). The data for these sprites are stored within the interpreter memory space (0x000 to 0x1FF).</p>
<pre><code class="language-plaintext">+------+----------+------+  +------+----------+------+
| "0"  |  Binary  | Hex  |  | "3"  |  Binary  | Hex  |
+------+----------+------+  +------+----------+------+
| **** | 11110000 | 0xF0 |  | **** | 11110000 | 0xF0 |
| *  * | 10010000 | 0x90 |  |    * | 00010000 | 0x10 |
| *  * | 10010000 | 0x90 |  | **** | 11110000 | 0xF0 |
| *  * | 10010000 | 0x90 |  |    * | 00010000 | 0x10 |
| **** | 11110000 | 0xF0 |  | **** | 11110000 | 0xF0 |
+------+----------+------+  +------+----------+------+
</code></pre>
<p>For now, we can simply throw these 8 x 5 bytes into memory for later use by modifying <code>CPU::new()</code> again.</p>
<pre><code class="language-rust">impl Cpu {
    pub fn new() -&gt; Cpu {
        let mut memory = [0; 4096];

        // load fonts into memory
        for i in 0..80 {
            memory[i] = FONTS[i];
        };

        Cpu {
            // ...
            memory: memory,
            // ...
        }
    }

    pub fn load_game(&amp;mut self, game: &amp;str) { /* ... */ }
}

static FONTS: [u8; 80] = [
  0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
  0x20, 0x60, 0x20, 0x20, 0x70, // 1
  0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
  0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
  0x90, 0x90, 0xF0, 0x10, 0x10, // 4
  0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
  0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
  0xF0, 0x10, 0x20, 0x40, 0x40, // 7
  0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
  0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
  0xF0, 0x90, 0xF0, 0x90, 0x90, // A
  0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
  0xF0, 0x80, 0x80, 0x80, 0xF0, // C
  0xE0, 0x90, 0x90, 0x90, 0xE0, // D
  0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
  0xF0, 0x80, 0xF0, 0x80, 0x80  // F
];
</code></pre>
<p><em>Thanks to</em> <a href="https://twitter.com/LaurenceMuller"><em>@LaurenceMuller</em></a><em>’s “</em><a href="http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/"><em>How to write an emulator</em></a><em>” [2] which already had a lot of this sorted.</em></p>
<h4>Emulate Cycle and Interpret data</h4>
<p>Now it’s time to do something with all this data! As we complete each cycle, grab the current opcode and interpret it.</p>
<blockquote>
<p>All instructions are 2 bytes long and are stored most-significant-byte first. In memory, the first byte of each instruction should be located at an even addresses. If a program includes sprite data, it should be padded so any instructions following it will be properly situated in RAM. [1]</p>
</blockquote>
<ul>
<li><em>nnn</em> or <em>addr</em> — A 12-bit value, the lowest 12 bits of the instruction</li>
<li><em>n</em> or <em>nibble</em> — A 4-bit value, the lowest 4 bits of the instruction</li>
<li><em>x</em> — A 4-bit value, the lower 4 bits of the high byte of the instruction</li>
<li><em>y</em> — A 4-bit value, the upper 4 bits of the low byte of the instruction</li>
<li><em>nn</em> or <em>byte</em> — An 8-bit value, the lowest 8 bits of the instruction</li>
</ul>
<pre><code class="language-rust">pub fn emulate_cycle(&amp;mut self) {
    self.fetch_opcode();
    self.execute_opcode();

    // okay, PCs are much faster these days
    // threw this cheeky delay in to slow things down
    thread::sleep(time::Duration::from_micros(500));
}

fn fetch_opcode(&amp;mut self) {
    self.opcode = (self.memory[self.program as usize] as u16) &lt;&lt; 8 | (self.memory[(self.program + 1) as usize] as u16);
}

fn execute_opcode(&amp;mut self) {
    match self.opcode &amp; 0xf000 {
        0x0000 =&gt; self.op_0xxx(),
        0x1000 =&gt; self.op_1xxx(),
        0x2000 =&gt; self.op_2xxx(),
        
        // .. remaining opcodes
        
        _ =&gt; not_implemented(self.opcode as usize, self.program)
    }
}

// Clear the display or Return from subroutine
fn op_0xxx(&amp;mut self) {
    match self.opcode &amp; 0x000F {
        0x0000 =&gt; { self.display.clear() }
        0x000E =&gt; {
            self.stack_pointer -= 1;
            self.program = self.stack[self.stack_pointer] as usize;
        }
        _ =&gt; { not_implemented(self.opcode as usize, self.program) }
    }
    self.program += 2;
}

// Jumps to address
fn op_1xxx(&amp;mut self) { self.program = self.op_nnn() as usize; }

// Calls subroutine
fn op_2xxx(&amp;mut self) {
    self.stack[self.stack_pointer] = self.program as u16;
    self.stack_pointer += 1;
    self.program = self.op_nnn() as usize;
}

fn op_x(&amp;self)   -&gt; usize { ((self.opcode &amp; 0x0F00) &gt;&gt; 8) as usize }
fn op_y(&amp;self)   -&gt; usize { ((self.opcode &amp; 0x00F0) &gt;&gt; 4) as usize }
fn op_n(&amp;self)   -&gt; u8 { (self.opcode &amp; 0x000F) as u8 }
fn op_nn(&amp;self)  -&gt; u8 { (self.opcode &amp; 0x00FF) as u8 }
fn op_nnn(&amp;self) -&gt; u16 { self.opcode &amp; 0x0FFF }
</code></pre>
<p>Complete list of opcodes: <a href="https://github.com/sean3z/chip8-emulator-rust/blob/master/src/cpu.rs#L81-L263">https://github.com/sean3z/chip8-emulator-rust/blob/master/src/cpu.rs</a></p>
<p>If you’re following along with Cowgod’s Technical Reference, all remaining opcodes can be implemented using the <a href="https://devernay.free.fr/hacks/chip8/C8TECH10.HTM#3.1">Standard Chip-8 Instructions</a></p>
<h3>References</h3>
<p>[1]: Cowgod’s Chip-8 Technical Reference, <em>Registers</em><a href="http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.2"><em>http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#2.2</em></a></p>
<p>[2]: moises’ blog: <em>Emulation Basics: Write your own Chip8 Interpreter</em><a href="http://omokute.blogspot.ca/2012/06/emulation-basics-write-your-own-chip-8.html"><em>http://omokute.blogspot.ca/2012/06/emulation-basics-write-your-own-chip-8.html</em></a></p>
<p>[3]: Laurence Muller: <em>How to write an emulator (Chip-8)</em><a href="http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/"><em>http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/</em></a></p>
<p>[4] Michalis Zamparas: <em>Chip-8 Rust implementation (Github)</em><a href="https://github.com/mikezaby/chip-8.rs"><em>https://github.com/mikezaby/chip-8.rs</em></a></p>
<p>[5] Colin Eberhardt: <em>Writing a CHIP-8 emulator with Rust and WebAssumbly</em><a href="http://blog.scottlogic.com/2017/12/13/chip8-emulator-webassembly-rust.html"><em>http://blog.scottlogic.com/2017/12/13/chip8-emulator-webassembly-rust.html</em></a></p>
]]></content:encoded></item><item><title><![CDATA[My C&C projects throughout the years]]></title><description><![CDATA[I’ve always loved the Command and Conquer series. In many ways, I owe my career to Tiberian Sun as it was primarily responsible for getting me into…]]></description><link>https://rambling.hashnode.dev/my-c-c-projects-throughout-the-years-23f429ef3d56</link><guid isPermaLink="true">https://rambling.hashnode.dev/my-c-c-projects-throughout-the-years-23f429ef3d56</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Wed, 21 Oct 2020 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/cd516a21-05be-4a12-9991-f1b25e4456f3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’ve always loved the <a href="https://en.wikipedia.org/wiki/Command_%26_Conquer">Command and Conquer</a> series. In many ways, I owe my career to <a href="https://en.wikipedia.org/wiki/Command_%26_Conquer:_Tiberian_Sun">Tiberian Sun</a> as it was primarily responsible for getting me into development in the first place.</p>
<p>For those unfamiliar, Tiberian Sun (and other C&amp;C titles) were largely popular <a href="https://en.wikipedia.org/wiki/Real-time_strategy">RTS</a> games in the late ’90s and early 2000s.</p>
<p>I’ve been enjoying <a href="https://www.ea.com/games/command-and-conquer/command-and-conquer-rivals">Rivals</a> for quite some time now and with <a href="https://www.ea.com/games/command-and-conquer/command-and-conquer-remastered">C&amp;C Remastered</a> released, this post is really just to reminisce about some of the fun C&amp;C projects I’ve worked on throughout the years. Have found the code to some of these projects and uploaded it to Github, others have likely been lost forever. Let’s be honest though, it was probably junk code anyway!</p>
<h2>Tiberian Sun Filter (TSF)</h2>
<p><em><strong>Tech used</strong></em>: mIRC Script, SQLite, Ethereal (Wireshark)<br /><em><strong>Source:</strong></em> <a href="https://bit.ly/31ujXWd">https://bit.ly/31ujXWd</a></p>
<p>There wasn’t a great way to track players back in the day and anyone could very easily spin up a new account. This small snippet would act as a relay/man-in-the-middle between the Tiberian Sun Game Client and XWIS Server and collect/associate IP information on players. It would then display all the alternative accounts they’ve used based on the association.</p>
<p>I learned A LOT on this project about Client/Server relationships. And how easily a Server can fault if validations aren’t put in place</p>
<p>In hindsight, this probably didn’t agree well with Westwood’s EULA 😅</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/76ee1a13-6b5f-4625-8c4e-68027a2f8fdb.png" alt="" style="display:block;margin:0 auto" />

<p>Yup, I’m <a href="https://medium.com/sean3z/create-ubuntu-server-virtual-guest-b32e0cbbe73a">KVMGuest</a>… don’t judge me.</p>
<h2>XWIS Player Index (XPI)</h2>
<p><em><strong>Tech used</strong></em>: Drupal, PHP, MySQL, Javascript</p>
<p>Eventually, friends wanted the same capability as TSF above. So decided to modify it and instead of writing to a local SQLite file, it’d publish to a hosted DB. Then built a UI via custom Drupal 6 modules for others to have the ability to lookup/comment on players. Cheating unfortunately also became rampant around this time. So XPI also became a way for players to identify those who played less than fair.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/4e0a9e57-75aa-4524-b608-cc5346dd627b.png" alt="" style="display:block;margin:0 auto" />

<p>hmm.. this looks an awful lot like <a href="https://www.drupal.org/case-study/symantec-connect-case-study">Symantec Connect</a>…</p>
<h2>Legacy C&amp;C Server Emulator</h2>
<p><em><strong>Tech used:</strong></em> <em>mIRC Script, MySQL</em><br /><em><strong>Source:</strong></em> <a href="http://hawkee.com/snippet/7709/">http://hawkee.com/snippet/7709/</a></p>
<p>I don’t remember when or why but, had a go at reverse-engineering the existing <a href="https://medium.com/sean3z/xwis-wol-game-server-protocol-b2a3457bd06">WOL Game Server Protocol</a> to recreate an alternative game server, dubbed CNC:EVO.</p>
<p>I’m not really sure what was “evolved” about it exactly but, it was thankfully, a short-lived, alternative to XWIS — who was the official server for legacy Command and Conquer games after taking over for Westwood Online (WOL).</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/f4e2ff21-bad3-4dc3-8bd9-a140a9123971.png" alt="" style="display:block;margin:0 auto" />

<h2>XWIS REST API</h2>
<p><em><strong>Tech used</strong></em>: PHP<br /><em><strong>Source:</strong></em> <a href="https://github.com/sean3z/api.xwis.org">https://github.com/sean3z/api.xwis.org</a></p>
<p>I wanted to include more stats about players in XPI but, XWIS only provided stats for players via HTML.</p>
<p>This project scraped the XWIS site and provided the same results via JSON. There weren’t many changes to the XWIS site, in fact, it’s likey the same now as it was then. So this API worked for quite some time and may even still work today 🤣</p>
<h2>XWIS Stats Signatures</h2>
<p><em><strong>Tech used</strong></em>*: PHP*<em><strong>Source:</strong></em> <a href="https://github.com/sean3z/xwis-signature">https://github.com/sean3z/xwis-signature</a></p>
<p>With the newfound API, and since forums — and bbcode forum signatures — were the rage back then, I thought it’d be cool to provide a dynamically generated forum signature. Clearly inspired by Battlefield, <a href="https://xwis.net/forums/index.php/topic/173568-xwis-stats-signatures/">these became pretty popular in the community</a>.</p>
<p>The “experience” below was my first attempt at continuous ladder progression for players, as the XWIS ladder reset every month.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/04a73507-906c-4a59-8453-27b9b3921383.png" alt="" style="display:block;margin:0 auto" />

<h2>XWIS.org Leaderboard</h2>
<p><em><strong>Tech used</strong></em>: PHP, MySQL, Javascript<br /><em><strong>Source:</strong></em> <a href="https://github.com/sean3z/xwis.org">https://github.com/sean3z/xwis.org</a></p>
<p>Building on the idea of a continuously progressive ladder, I built out a site using similar logic. This became a widely used unofficial ladder in the community — in fact, <a href="https://xwis.net/forums/index.php/topic/180996-xwisorg/">many people wanted it to become to the official ladder</a> and <a href="https://xwis.net/forums/index.php/topic/184212-where-are-the-xwisorg-domain">were disappointed</a> when I decided to focus on other projects.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/04cfc330-3263-413d-add0-e3c2b9c74444.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/4828913d-1ceb-444d-8565-75c80964aa71.png" alt="" style="display:block;margin:0 auto" />

<p>Had to find screenshots via the Wayback machine!</p>
<h2>XWISAdmin Web Interface</h2>
<p><em><strong>Tech used</strong></em>: Node, <a href="http://Socket.io">Socket.io</a><br /><em><strong>Source:</strong></em> <a href="https://github.com/sean3z/xwisadmin">https://github.com/sean3z/xwisadmin</a></p>
<p>Given my XWIS hijinks and contributions to the community, I earned a <a href="https://xwis.net/forums/index.php/topic/174493-welcome-sean3z-to-help-team/">spot on the XWIS Help Team</a>, and shortly after was <a href="https://xwis.net/forums/index.php/topic/174834-welcome-sean3z-to-the-analyser-team-for-ts/">promoted to the XWIS Admin team</a>. The way the XWIS Admin bot was controlled was <em>really</em> outdated at this point; this project converted/replaced it with a real-time Web Interface.</p>
<p>This was basically a websocket over an IRC-like server; nothing fancy but, better than launching the Game Client to manage the Server.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/6dfab707-0bbe-402d-b593-694e5b1fb451.png" alt="" style="display:block;margin:0 auto" />

<h2>Tiberian Sun Facebook Admin</h2>
<p>As part of the team, I even got to create content for a while on the Official <a href="https://www.facebook.com/CNCTiberianSun">Command and Conquer: Tiberian Sun</a> Facebook page. One particular post which became semi-viral was when the <a href="https://en.wikipedia.org/wiki/Keep_Calm_and_Carry_On">KEEP CALM</a> craze was coming back at the time, so naturally had to put my own spin on it…</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/e2566a22-d550-4e35-8911-718ab1ae2197.png" alt="" style="display:block;margin:0 auto" />

<h2>CnCNet REST API</h2>
<p><em><strong>Tech used</strong></em>*: Node, Restify, MongoDB*<em><strong>Source:</strong></em> <a href="https://github.com/sean3z/cncnet-api">https://github.com/sean3z/cncnet-api</a></p>
<p>So by this point, XWIS was on the decline and <a href="https://cncnet.org/">CnCNet</a> was on the rise. CnCNet is a great project with a lot of community support — and is likely still the best place to play legacy C&amp;C games. CnCNet didn’t have a ladder at the time though, so this was the first “official” ladder. Unlike XWIS where I was scraping/reparsing stats, the game clients sent data directly to my endpoints via some <a href="https://github.com/CnCNet/ts-patches">pretty intense patches</a>.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/19a37a4b-b5a8-4905-a41d-d63fec201b42.png" alt="" style="display:block;margin:0 auto" />

<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/adfb9b67-e9b9-4efb-9ec4-0f11610f556e.png" alt="" style="display:block;margin:0 auto" />

<h2>CnCNet Leaderboard UI</h2>
<p><em><strong>Tech used</strong></em>: Angular, Node<br /><em><strong>Source:</strong></em> <a href="https://github.com/sean3z/cncnet-leaderboard">https://github.com/sean3z/cncnet-leaderboard</a></p>
<p>And what’s the point of having an API, without a slick UI to display the results? Mostly thanks to <a href="https://github.com/GrantBartlett">Neogrant</a> on this one — he’s become into one heck of a Front End engineer!</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/801af8f6-68af-4491-8532-3848d4e245eb.png" alt="" style="display:block;margin:0 auto" />

<h2>CnCNet Client (incomplete)</h2>
<p><em><strong>Tech used</strong></em>: Electron, Angular, Node<br /><em><strong>Source:</strong></em> <a href="https://github.com/sean3z/cncnet-client">https://github.com/sean3z/cncnet-client</a></p>
<p>This was a stab at learning more about Electron and attempting to building a custom client on the CnCNet foundation. Didn’t really go anywhere but, was certainly a lot of fun!</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/21115281-9b91-4ebe-bcf6-3710ce5ed82f.png" alt="" style="display:block;margin:0 auto" />

<h2>Westwood Online (WOL) Documentation</h2>
<p>I know I’ve written more on how the WOL/XWIS server works than I’d like to admit but, could only find the following.</p>
<ul>
<li><a href="https://medium.com/sean3z/xwis-wol-game-server-protocol-b2a3457bd06">Game Server Protocol</a></li>
<li><a href="https://medium.com/sean3z/wol-apgar-routine-2187ec567d86">APGAR password hash routine</a></li>
</ul>
<h2>Conclusion</h2>
<p>I’ve learned a lot through these, had a lot of fun, and met a lot of great people. And it’s been a ton of fun reminiscing about these projects! Command and Conquer has been a big part of my life and glad to see it making a bit of a comeback.</p>
<p>These days I’m still enjoying time on <a href="https://www.ea.com/games/command-and-conquer/command-and-conquer-rivals">Rivals</a> — and the alliance I founded (during the Alpha release!) aptly named “Tiberian Sun”, typically remains on the Top 25 Leaderboard!</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/210b87ea-269d-401d-8376-fe91970aec17.jpg" alt="" style="display:block;margin:0 auto" />

<p>See you on the battlefield Commander!</p>
]]></content:encoded></item><item><title><![CDATA[Get around CourseHero or Quizlet]]></title><description><![CDATA[Monthly limits seem to be on the rise as a means to mandate user sign up or subscription enrollment and is very commonly seen on News/Journal sites…]]></description><link>https://rambling.hashnode.dev/get-around-coursehero-or-quizlet-8f6ed958ffdc</link><guid isPermaLink="true">https://rambling.hashnode.dev/get-around-coursehero-or-quizlet-8f6ed958ffdc</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 24 Feb 2019 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Monthly limits seem to be on the rise as a means to mandate user sign up or subscription enrollment and is very commonly seen on News/Journal sites.</p>
<p>However, the technical approach in which some sites implemented this wall — could really use some reevaluation.</p>
<h3><strong>Steps to circumvent CourseHero</strong>:</h3>
<ul>
<li>Open DevTools (right click &gt; Inspect)</li>
<li>Paste in the following snippet into the Console tab and hit Enter</li>
</ul>
<p>Paste this code into the Console Tab of DevTools</p>
<pre><code class="language-javascript">let content = document.querySelector('main.bdp_docViewerWide_main');
$('.bdp_doc-viewer_notification').after(content.innerHTML);
$('.mfp-bg.mfp-ready, .mfp-content').hide();
document.querySelector('body').style.overflow = 'auto';
</code></pre>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/9099c7f5-8e15-473a-ba6d-755a4e418f0e.gif" alt="" style="display:block;margin:0 auto" />

<h3>Steps to circumvent Quizlet:</h3>
<ul>
<li>Open DevTools (right click &gt; Inspect)</li>
<li>Paste in the following snippet into the Console tab and hit Enter</li>
</ul>
<pre><code class="language-javascript">let terms = document.querySelectorAll('.SetPageTerm.has-definitionText, .SetPageTerms-termsList');
for (let term of terms) term.classList.add('is-showing');
document.querySelector('.SignupWallInline').style.display = 'none';
</code></pre>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/1d8c27cd-06f1-4221-a3d0-e46ef9e1a409.gif" alt="" style="display:block;margin:0 auto" />

<h3><strong>Yeah but, why?</strong></h3>
<p>Ultimately, it should take more than 3 lines of javascript (technically all CSS) to bypass your sign up call-to-action — regardless of whether you need the SEO credit.</p>
<p>Not to get too high-horse here but, this is just lazy development. And these guys aren’t the only ones!</p>
<p>Undoubtedly, an argument could be made their approach has some level of effectiveness against those users who know nothing about web but, meh..</p>
<p>Hopefully shedding light on these circa ‘99 practices, will prompt sites to take web security more serious — especially if you’re offering paid services and adverting Tech jobs via console!</p>
]]></content:encoded></item><item><title><![CDATA[Thoughts: The Best Man (Batman #48)]]></title><description><![CDATA[“THE BEST MAN” part one! Batman and Catwoman decide it might be better to elope rather than go through some big, stodgy wedding ceremony, but no sooner do…]]></description><link>https://rambling.hashnode.dev/the-best-man-batman-48-d1e5cce65808</link><guid isPermaLink="true">https://rambling.hashnode.dev/the-best-man-batman-48-d1e5cce65808</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Wed, 06 Jun 2018 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/86321582-de0c-4317-905d-36e05292e7d9.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/0e067be9-86c1-458b-81d5-4762fc68256c.jpg" alt="" /></p>
<blockquote>
<p>“THE BEST MAN” part one! Batman and Catwoman decide it might be better to elope rather than go through some big, stodgy wedding ceremony, but no sooner do they put their marriage on the fast track than The Joker appears! And when The Joker kidnaps the Caped Crusader, will he give his old foe a piece of his mind or bash in his brains?</p>
</blockquote>
<p>As we narrow closer to the epic Batman/Catwoman wedding, an (un?)expected surprise appearance by the Joker may derail their plans.</p>
<p>Sharing some thoughts on Batman #48</p>
<h4><strong>Spoilers below, in…</strong></h4>
<p>3…</p>
<p>2…</p>
<p>1…</p>
<p>This issue opens full throttle right out of the gate. Joker is mercilessly executing wedding members at a Gotham church to get Batman’s attention.</p>
<p>Yet somehow we already know this isn’t going to be the typical catch-and-release Arkham Inmate 0801 encounter. And it’s incredible that Joker knows Batman so well, that he predicts exactly when Bats make his entrance — which gives us a great nod to the ‘66 Adam West Batman (RIP):</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/2c2dcd76-66f4-4bca-a374-de4ebeb6c9fb.png" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/97f23326-2e07-4cba-b1d0-48432566d35f.png" alt="" /></p>
<p>© DC Comics 2018</p>
<p>In Part 1 of ‘The Best Man’, Joker clearly wants to convey some twisted story about love to Batman — in only a way Joker can. He decides to use a hostage to delay the inevitable beatdown Bats will dish, but after an accidental discharge — the hostage is quickly dispatched.</p>
<p>Unable to find anyone else alive, Joker holds himself hostage (Blazing Saddles anyone?) to continue telling his dark story.</p>
<p>He kneels at the alter and instructs Batman to pray with him, then pops the question we all knew was coming:</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/e8791755-4c96-426e-b821-d71fb28f0ec9.png" alt="" /></p>
<p>© DC Comics 2018</p>
<p>It’s no secret that Batman and Joker have a… special relationship. Greatly looking forward to Part 2 of what will very likely impact the Bat/Cat wedding!</p>
<p>This issue ends with Catwoman on her way, presumably against Batman’s instructions, to rescue the man she intends to wed.</p>
<p>King has created a very compelling lead to an event in which many are looking forward. As always, Janin and Chung continue to dazzle with great art and rich colors.</p>
<p>Unfortunately, this reader is left with more questions than answers!</p>
<ul>
<li>Is there a reason Joker chose “this” wedding to violently interrupt?</li>
<li>How will Batman react?</li>
<li>And why <em>exactly</em> does Joker want to be The Best Man?</li>
</ul>
<p>Hopefully we’ll find out in Part 2, next time. Same Bat-time; same Bat-channel!</p>
]]></content:encoded></item><item><title><![CDATA[Build a CRUD API with Rust]]></title><description><![CDATA[Update 10/25/2026: I wrote this guide against Rocket 0.3 and Diesel 1, which meant nightly Rust and a handful of codegen crates. That setup doesn’t build…]]></description><link>https://rambling.hashnode.dev/building-a-restful-crud-api-with-rust-1867308352d8</link><guid isPermaLink="true">https://rambling.hashnode.dev/building-a-restful-crud-api-with-rust-1867308352d8</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Mon, 19 Mar 2018 00:00:00 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p><em>Update 10/25/2026: I wrote this guide against Rocket 0.3 and Diesel 1, which meant nightly Rust and a handful of codegen crates. That setup doesn’t build anymore (a few of you let me know on GitHub, thank you!). So I’ve updated the code samples and the</em> <a href="https://github.com/sean3z/rocket-diesel-rest-api-example"><em>companion repo</em></a> <em>for Rocket 0.5 and Diesel 2 on stable Rust. You can skip the nightly toolchain entirely. The routes, the migration and the overall flow haven’t changed, and the benchmarks further down are still the original 2018 numbers</em></p>
</blockquote>
<p>Since my initial <a href="https://medium.com/sean3z/rest-api-node-vs-rust-c75aa8c96343">Node/Rust REST comparison</a>, I’ve wanted to follow up with a comprehensive guide for getting simple CRUD operations up and running in Rust.</p>
<p>While Rust has its complexities, coming from Node.js, one thing that’s kept me attracted to the language is its simplicity. It’s sleek and strikes a great balance between safety and cognitive intuition.</p>
<p>In any event, hopefully this guide helps those that are new to Rust and encourages those who are on the fence.</p>
<p><em>Scroll down if you’d like to see how Rust compares against</em> <em><strong>Java</strong></em> <em>and</em> <em><strong>Node.js</strong></em></p>
<h3>Major frameworks used</h3>
<ul>
<li><a href="https://rocket.rs/">Rocket</a> — <em>web framework for writing fast web applications</em></li>
<li><a href="https://serde.rs/">Serde</a> — <em>framework for</em> <strong>ser</strong><em>ializing and</em> <strong>de</strong><em>serializing Rust data structures</em></li>
<li><a href="http://diesel.rs/">Diesel</a> — <em>safe, extensible ORM and query builder</em></li>
</ul>
<h3>Creating our application in Rust</h3>
<p>First, we’ll create a new Rust project using the commands below.</p>
<pre><code class="language-shell">[sean@lappy486:~] $ cargo new hero-api --bin &amp;&amp; cd hero-api
    Created binary (application) `hero-api` project
</code></pre>
<p>Thankfully, Rocket doesn’t need nightly Rust anymore. Since Rocket 0.5, everything here builds on stable, so if you have a recent toolchain from rustup you’re already set. If you switched to nightly for the original version of this post, here’s how to switch back</p>
<pre><code class="language-shell">$ rustup default stable
$ rustup update
</code></pre>
<p>You can confirm the switch by checking the versions of cargo and rustc. Any current stable release works</p>
<h3>Adding our first Rust dependency (Rocket)</h3>
<p>Alright, within our <code>hero-api</code> directory, you’ll find a <code>Cargo.toml</code> and <code>src</code> folder. <code>Cargo.toml</code> will act similar to Node’s <code>package.json</code> which we’ll cover later — and I suspect <code>src</code> is descriptive enough :)</p>
<p>We’ll need to add Rocket as a dependency by editing Cargo.toml. There’s more to add later, but this one line gets us started (it used to take two, back when Rocket needed a separate codegen crate)</p>
<pre><code class="language-plaintext">[dependencies]
rocket = "0.5"
</code></pre>
<p>Now we can edit <code>src/main.rs</code> — we’ll just borrow the <a href="https://rocket.rs/guide/v0.5/getting-started/#hello-world">starter code provided to us by Rocket.rs</a> to ensure everything works at this point.</p>
<pre><code class="language-rust">#[macro_use]
extern crate rocket;

#[get("/&lt;name&gt;/&lt;age&gt;")]
fn hello(name: &amp;str, age: u8) -&gt; String {
    format!("Hello, {} year old named {}!", age, name)
}

#[launch]
fn rocket() -&gt; _ {
    rocket::build().mount("/hello", routes![hello])
}
</code></pre>
<p>The thing that I find most appealing about Rust (and Rocket) is how self descriptive the majority of the code is.</p>
<pre><code class="language-rust">#[get("/&lt;name&gt;/&lt;age&gt;")]
</code></pre>
<p>Here we expose a single endpoint, using Rocket’s attribute, that takes two parameters &lt;name&gt; and &lt;age&gt;. We then map those parameters to our route handler and give them types. If a value doesn’t match its type (say, an age of “old”), the handler isn’t called and Rocket responds with a 422 instead</p>
<pre><code class="language-rust">fn hello(name: &amp;str, age: u8) -&gt; String {
</code></pre>
<p>Our route handler returns a formatted<code>String</code>, using Rust’s <a href="https://doc.rust-lang.org/std/fmt/">format!</a> macro, with the supplied <code>name</code> and <code>age</code>. Notice no trailing semicolon for return statements</p>
<pre><code class="language-rust">format!("Hello, {} year old named {}!", age, name)
</code></pre>
<p>Rocket 0.5 replaces the old main function with the #[launch] attribute. It builds our Rocket instance and mounts the route handler with /hello as the root context, then Rocket handles the rest of the startup. That gives us a URL like /hello/&lt;name&gt;/&lt;age&gt;</p>
<pre><code class="language-rust">#[launch]
fn rocket() -&gt; _ {
    rocket::build().mount("/hello", routes![hello])
}
</code></pre>
<p>Let’s test that everything works by starting our server with cargo run. This starts a server on localhost:8000 which you can hit from a browser, curl, etc</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/9f74f6d7-9ecb-4500-98fa-b479b8819193.png" alt="" style="display:block;margin:0 auto" />

<h3>Building Restful endpoints using JSON (Serde)</h3>
<p>So, one endpoint will only get us so far. Thinking about our API, we want simple <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete">CRUD</a> operations to manage Hero data; so right off the top, we’ll want:</p>
<ul>
<li>Create:<code>POST /hero</code></li>
<li>Read: <code>GET /heroes</code></li>
<li>Update: <code>PUT /hero/:id</code></li>
<li>Delete: <code>DELETE /hero/:id</code></li>
</ul>
<p>Now that we have that out of the way — we’ll be using JSON as our primary means for exchanging data, so in comes our next dependency: <a href="https://serde.rs/">Serde</a>.</p>
<p>This used to mean four extra crates. Now it’s just Serde with its derive feature, plus Rocket’s built-in json feature (rocket_contrib is gone)</p>
<pre><code class="language-plaintext">[package]
name = "hero-api"
version = "0.1.0"
edition = "2021"

[dependencies]
rocket = { version = "0.5", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
</code></pre>
<p>We’ll also want to think about what properties a given Hero should have. Below we create a simple Hero model in src/hero.rs, adding Serde’s Serialize and Deserialize derives so our model can be converted to and from JSON</p>
<pre><code class="language-rust">use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Hero {
    pub id: Option&lt;i32&gt;,
    pub name: String,
    pub identity: String,
    pub hometown: String,
    pub age: i32,
}
</code></pre>
<p><code>id</code> is Optional since consumers hitting our CREATE endpoint will not yet have an id to send. However, when we retrieve data and supply it as a response, anything from our DB will have an id established.</p>
<p>Let’s go ahead and create our CRUD endpoints now, using dummy data for the time being:</p>
<pre><code class="language-rust">#[macro_use]
extern crate rocket;

use rocket::serde::json::{json, Json, Value};

mod hero;
use hero::Hero;

#[post("/", data = "&lt;hero&gt;")]
fn create(hero: Json&lt;Hero&gt;) -&gt; Json&lt;Hero&gt; {
    hero
}

#[get("/")]
fn read() -&gt; Json&lt;Value&gt; {
    Json(json!([
        "hero 1",
        "hero 2"
    ]))
}

#[put("/&lt;id&gt;", data = "&lt;hero&gt;")]
fn update(id: i32, hero: Json&lt;Hero&gt;) -&gt; Json&lt;Hero&gt; {
    hero
}

#[delete("/&lt;id&gt;")]
fn delete(id: i32) -&gt; Json&lt;Value&gt; {
    Json(json!({"status": "ok"}))
}

#[launch]
fn rocket() -&gt; _ {
    rocket::build()
        .mount("/hero", routes![create, update, delete])
        .mount("/heroes", routes![read])
}
</code></pre>
<p>In the above, we pull in our Hero type, along with Json, Value and the json! macro from Rocket’s serde module. These make it easier to deal with JSON requests and responses</p>
<pre><code class="language-rust">use rocket::serde::json::{json, Json, Value};
mod hero;
use hero::Hero;
</code></pre>
<p>We also add our other operations (POST, PUT, DELETE). The <code>data</code> attribute within our route annotation simply tells Rocket to expect <a href="https://rocket.rs/guide/requests/#body-data">Body Data</a> — then map the body to a parameter. Here we say, the body expected should be in the form of a Hero but wrapped in JSON.</p>
<pre><code class="language-rust">#[post("/", data = "&lt;hero&gt;")]
fn create(hero: Json&lt;Hero&gt;) -&gt; Json&lt;Hero&gt; {
</code></pre>
<p>We should now be able to hit any of our configured endpoints using a standard rest client/curl, etc.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/84831ce5-88b4-40c4-825c-3e89485f15ef.png" alt="" style="display:block;margin:0 auto" />

<h3>Persisting our data via ORM (Diesel)</h3>
<p>I think we can all agree, having a few URLs is great but, not too helpful if the data we’re sending isn’t persisted. For this, we’ll use <a href="http://diesel.rs/">Diesel</a> as it’s currently one of the most mature Rust ORM frameworks.</p>
<p>Doing this for the first time, I’ll admit, is certainly an involved process but once the initial bootstrap is out of the way, it works quite well. I’ve <a href="https://github.com/pwfantasy/pwfantasy-api/blob/master/src/talent.rs">tried</a> this with the <a href="https://github.com/blackbeam/rust-mysql-simple">blackbeam raw mysql driver</a>, and while it works, the codebase becomes polluted really quick..</p>
<p>In fact, <a href="https://medium.com/u/38fe29eb5d42">Sean Griffin</a> (author of Diesel) wrote a <a href="https://hackernoon.com/comparing-diesel-and-rust-postgres-97fd8c656fdd">great article</a> illustrating this very point.</p>
<p>To get started, we install the Diesel CLI with just MySQL support. It’s worth noting that you’ll need the MySQL client library and headers (libmysqlclient) installed for this and for building the app</p>
<pre><code class="language-shell">$ cargo install diesel_cli --no-default-features --features mysql
</code></pre>
<p>Then we tell Diesel where our database should live and run setup:</p>
<pre><code class="language-shell">$ export DATABASE_URL=mysql://user:pass@localhost/heroes
$ diesel setup
    Creating migrations directory at: ~/hero-api/migrations
    Creating database: heroes
</code></pre>
<p>Next, we’ll generate a migration strategy — this basically allows us to keep revisions as our database evolves over time.</p>
<pre><code class="language-shell">$ diesel migration generate heroes
    Creating migrations/2018-03-17-180012_heroes/up.sql
    Creating migrations/2018-03-17-180012_heroes/down.sql
</code></pre>
<p>We’ll need to edit these two files to include the SQL for our Heroes schema</p>
<pre><code class="language-sql">-- down.sql
DROP TABLE heroes;
</code></pre>
<pre><code class="language-sql">-- up.sql
CREATE TABLE heroes (
  id INT(11) PRIMARY KEY AUTO_INCREMENT,
  `name` VARCHAR(60) NOT NULL,
  identity VARCHAR(60) NOT NULL,
  hometown VARCHAR(60) NOT NULL,
  age INT(11) NOT NULL
)
</code></pre>
<p>Now we can run our migration — which will execute up.sql against our DB</p>
<pre><code class="language-shell">[sean@lappy486:~/hero-api] $ diesel migration run
    Running migration 2018-03-17-180012_heroes
</code></pre>
<p>With any luck, that’s the last SQL we should touch for this project. Let’s go ahead and add Diesel to our dependencies in Cargo.toml. Connection pooling (r2d2) is built into Diesel 2 now, so a feature flag replaces the three extra crates I used originally</p>
<pre><code class="language-plaintext">[dependencies]
diesel = { version = "2", features = ["mysql", "r2d2"] }
</code></pre>
<p>We’ll create src/db.rs to set up our database connection and manage our pool. It’s still a custom request guard built on Rocket’s managed state, it’s just async now. It also reads DATABASE_URL when the server starts instead of at compile time, so you’ll need it set whenever you run the app</p>
<pre><code class="language-rust">use std::ops::{Deref, DerefMut};

use diesel::mysql::MysqlConnection;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome, Request};
use rocket::State;

/// An alias to the type for a pool of Diesel MySQL connections.
pub type MysqlPool = Pool&lt;ConnectionManager&lt;MysqlConnection&gt;&gt;;

/// Initialize the database pool from the `DATABASE_URL` environment variable.
pub fn connect() -&gt; MysqlPool {
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let manager = ConnectionManager::&lt;MysqlConnection&gt;::new(database_url);
    Pool::builder()
        .build(manager)
        .expect("Failed to create pool")
}

/// Connection request guard: a wrapper around an r2d2 pooled connection.
pub struct Connection(pub PooledConnection&lt;ConnectionManager&lt;MysqlConnection&gt;&gt;);

/// Attempts to retrieve a single connection from the managed database pool. If
/// no pool is currently managed, fails with an `InternalServerError` status. If
/// no connections are available, fails with a `ServiceUnavailable` status.
#[rocket::async_trait]
impl&lt;'r&gt; FromRequest&lt;'r&gt; for Connection {
    type Error = ();

    async fn from_request(request: &amp;'r Request&lt;'_&gt;) -&gt; Outcome&lt;Self, Self::Error&gt; {
        let pool = match request.guard::&lt;&amp;State&lt;MysqlPool&gt;&gt;().await {
            Outcome::Success(pool) =&gt; pool,
            Outcome::Error(error) =&gt; return Outcome::Error(error),
            Outcome::Forward(_) =&gt; {
                return Outcome::Error((Status::InternalServerError, ()));
            }
        };

        match pool.get() {
            Ok(conn) =&gt; Outcome::Success(Connection(conn)),
            Err(_) =&gt; Outcome::Error((Status::ServiceUnavailable, ())),
        }
    }
}

impl Deref for Connection {
    type Target = MysqlConnection;

    fn deref(&amp;self) -&gt; &amp;Self::Target {
        &amp;self.0
    }
}

impl DerefMut for Connection {
    fn deref_mut(&amp;mut self) -&gt; &amp;mut Self::Target {
        &amp;mut self.0
    }
}
</code></pre>
<p>We’ll also need to make the following additions to bind our Hero model with the new table info we’ve created:</p>
<pre><code class="language-rust">use diesel::mysql::MysqlConnection;
use diesel::prelude::*;
use serde::{Deserialize, Serialize};

use crate::schema::heroes;

#[derive(AsChangeset, Serialize, Deserialize, Queryable, Insertable)]
#[diesel(table_name = heroes)]
pub struct Hero {
    #[diesel(deserialize_as = i32)]
    pub id: Option&lt;i32&gt;,
    pub name: String,
    pub identity: String,
    pub hometown: String,
    pub age: i32,
}
</code></pre>
<p>table_name points our struct at the heroes table, which Diesel describes for us in src/schema.rs. You don’t need to run diesel print-schema yourself here, because diesel setup created a diesel.toml that rewrites src/schema.rs every time we run a migration</p>
<pre><code class="language-rust">// @generated automatically by Diesel CLI.

diesel::table! {
    heroes (id) {
        id -&gt; Integer,
        #[max_length = 60]
        name -&gt; Varchar,
        #[max_length = 60]
        identity -&gt; Varchar,
        #[max_length = 60]
        hometown -&gt; Varchar,
        age -&gt; Integer,
    }
}
</code></pre>
<p>We’re still using one model for both Queryable and Insertable. The Diesel author gave fair reasoning for splitting it into two, but I prefer the convenience and less code pollution. In the original post I got there by hand-editing src/schema.rs, and that edit would now get overwritten on the next migration. Thankfully, #[diesel(deserialize_as = i32)] handles it on the struct itself. Rows from the database always come back with an id, inserts with id: None let MySQL assign one, and AsChangeset skips the primary key on updates</p>
<p>Without that attribute, we’d need two models: one to insert (without id) and a separate one to retrieve (with id)</p>
<p>Now we can pull in these new modules by adding the following to src/main.rs. Diesel 2 doesn’t need any extern crate lines</p>
<pre><code class="language-rust">mod db;
mod schema;
</code></pre>
<p>Next we’ll tell Rocket to manage our db connection pool by adding the following to our rocket::build() chain</p>
<pre><code class="language-rust">.manage(db::connect())
</code></pre>
<p>Believe it or not, now we’re ready to get this thing going! Here we’ll expose a few methods by creating an implementation for Hero within src/hero.rs, minus any fancy error handling. The main difference from the original is that Diesel 2 queries take a &amp;mut connection</p>
<pre><code class="language-rust">impl Hero {
    pub fn create(hero: Hero, connection: &amp;mut MysqlConnection) -&gt; Hero {
        diesel::insert_into(heroes::table)
            .values(&amp;hero)
            .execute(connection)
            .expect("Error creating new hero");

        heroes::table
            .order(heroes::id.desc())
            .first(connection)
            .unwrap()
    }

    pub fn read(connection: &amp;mut MysqlConnection) -&gt; Vec&lt;Hero&gt; {
        heroes::table.order(heroes::id).load(connection).unwrap()
    }

    pub fn update(id: i32, hero: Hero, connection: &amp;mut MysqlConnection) -&gt; bool {
        diesel::update(heroes::table.filter(heroes::id.eq(id)))
            .set(&amp;hero)
            .execute(connection)
            .is_ok()
    }

    pub fn delete(id: i32, connection: &amp;mut MysqlConnection) -&gt; bool {
        diesel::delete(heroes::table.filter(heroes::id.eq(id)))
            .execute(connection)
            .is_ok()
    }
}
</code></pre>
<p>Now we can leverage the newly created methods within our route handlers</p>
<pre><code class="language-rust">#[macro_use]
extern crate rocket;

use rocket::serde::json::{json, Json, Value};

mod db;
mod hero;
mod schema;

use hero::Hero;

#[post("/", data = "&lt;hero&gt;")]
fn create(hero: Json&lt;Hero&gt;, mut connection: db::Connection) -&gt; Json&lt;Hero&gt; {
    let insert = Hero { id: None, ..hero.into_inner() };
    Json(Hero::create(insert, &amp;mut connection))
}

#[get("/")]
fn read(mut connection: db::Connection) -&gt; Json&lt;Value&gt; {
    Json(json!(Hero::read(&amp;mut connection)))
}

#[put("/&lt;id&gt;", data = "&lt;hero&gt;")]
fn update(id: i32, hero: Json&lt;Hero&gt;, mut connection: db::Connection) -&gt; Json&lt;Value&gt; {
    let update = Hero { id: Some(id), ..hero.into_inner() };
    Json(json!({
        "success": Hero::update(id, update, &amp;mut connection)
    }))
}

#[delete("/&lt;id&gt;")]
fn delete(id: i32, mut connection: db::Connection) -&gt; Json&lt;Value&gt; {
    Json(json!({
        "success": Hero::delete(id, &amp;mut connection)
    }))
}

#[launch]
fn rocket() -&gt; _ {
    rocket::build()
        .manage(db::connect())
        .mount("/hero", routes![create, update, delete])
        .mount("/heroes", routes![read])
}
</code></pre>
<p>Notice, each method within our route handlers and Hero implementation now essentially accept the same/similar arguments: Some combination of an <code>id</code>, <code>Hero</code> object and database <code>connection</code>.</p>
<p><em>For more info on how to query data, refer to the</em> <a href="http://diesel.rs/guides/"><em>Diesel Getting Started</em></a> <em>guides.</em></p>
<p>Finally, we can now create a Hero and see real results in our REST Client. Fetching, updating and deleting Heroes also work as expected.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/4964a770-0b48-498d-9ca4-121289c6149c.png" alt="" style="display:block;margin:0 auto" />

<h3>Putting our API to the test (wrk)</h3>
<p><em>Sidenote: everything in this section is from the original 2018 run (Rocket 0.3 on nightly Rust 1.26), and I haven’t re-run it on Rocket 0.5. Read the numbers as a snapshot of that setup, not as current results</em></p>
<p>Now that we have a somewhat complete API, it’s probably worth benchmarking this thing as one of the most touted aspect of Rust is its performance over other languages.</p>
<p>But before trying it out, I wanted to get an idea of how other popular languages and frameworks stack up.</p>
<p>For this, I simply used <a href="https://github.com/wg/wrk"><code>wrk</code></a> locally on my Macbook Pro with no other user applications or services running.</p>
<pre><code class="language-plaintext">MacBook Pro (15-inch, 2016) 
Processor:  2.9 GHz Intel Intel Core i7 
Memory: 16 GB 2133 MHz LPDDR3 
Storage:    1 TB Flash Storage
</code></pre>
<h3>Java 1.8 (Spring Boot, Hibernate)</h3>
<p>I threw together a quick example exposing the same GET Heroes method that we created in our Rust API above by following a great tutorial by <a href="https://medium.com/u/85e837d6b502">Rajeev Kumar Singh</a> (<a href="https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/">found here</a>)</p>
<p>The example code used can be found here:</p>
<ul>
<li><p><a href="https://github.com/sean3z/spring-boot-hero-api-example">https://github.com/sean3z/spring-boot-hero-api-example</a></p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/c55ff030-b744-4ffb-bfa0-5434ea17a5c2.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<p>The results weren’t bad @ <strong>4,584</strong> requests per second</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/d6a7ff3a-ff27-46f2-ae9f-b39fb9a454d1.png" alt="" style="display:block;margin:0 auto" />

<h3>Node 9.8 (Restify, Sequelize)</h3>
<p>The Node team has made significant improvements in Node 9. Now leveraging <a href="https://v8project.blogspot.com/2017/05/launching-ignition-and-turbofan.html">V8’s Ignition and Turbofan</a> — Node’s performance has nearly tripled.</p>
<p>The example code used can be found here:</p>
<ul>
<li><p><a href="https://github.com/sean3z/nodejs-hero-api-example">https://github.com/sean3z/nodejs-hero-api-example</a></p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/33298ce1-bff2-4ef6-8ffd-9b125ef07983.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<p>The results weren’t nearly what I was hoping @ <strong>2,506</strong> requests per second. It’s worth noting that using the raw <code>mysql</code> package nearly doubled the handled requests per second.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/d021abe9-047c-49ac-bb91-e63e6a0246cb.png" alt="" style="display:block;margin:0 auto" />

<h3>Rust 1.26 (Rocket, Diesel)</h3>
<p>Finally, to test our Rust server, we’ll build in release mode. In 2018 that also meant setting ROCKET_ENV=prod. Rocket 0.5 picks its release profile automatically for release builds, so now we only pass the address and port</p>
<pre><code class="language-plaintext">$ cargo build --release &amp;&amp; cd target/release/
$ sudo ROCKET_ADDRESS=0.0.0.0 ROCKET_PORT=80 ./hero-api
    Rocket has launched from http://0.0.0.0:80
</code></pre>
<p>The example code used can be found here:</p>
<ul>
<li><p><a href="https://github.com/sean3z/rocket-diesel-rest-api-example">https://github.com/sean3z/rocket-diesel-rest-api-example</a></p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/c913597b-4f92-451c-8d3e-58fda4b91188.png" alt="" style="display:block;margin:0 auto" /></li>
</ul>
<p>Rust seriously outperformed both of the other frameworks</p>
<img src="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/a6455507-0330-4261-bda9-603b27361888.png" alt="" style="display:block;margin:0 auto" />

<h3>Conclusion</h3>
<p>Node provided the smallest code footprint but, obviously without type safety and on the lower end of the performance scale — although, 2k req/sec is nothing to scoff at. We can improve Node’s performance at the cost of nastier code maintenance.</p>
<p>Java had <em>by far</em> the largest code footprint. It also takes the longest to start up at an average ~4seconds. Not really much else to report here, it just wasn’t.. fun to develop?</p>
<p>Rust is a tremendously fun language to use and it’s blazingly fast. It goes without saying, speed isn’t the only factor when considering the right tool for the job but, it’s certainly an important one.</p>
<p><em>To learn more about Rust, check out the “</em><a href="https://doc.rust-lang.org/book/"><em>The Rust Programming Language</em></a><em>”</em></p>
]]></content:encoded></item><item><title><![CDATA[Don’t let SMS Spam phish you!]]></title><description><![CDATA[Phishing scams aren’t anything new. If you’ve lived through the early days of the interwebs, you can probably recall a couple of run-ins with a phony…]]></description><link>https://rambling.hashnode.dev/dont-let-sms-spam-phish-you-8b7033dfc67a</link><guid isPermaLink="true">https://rambling.hashnode.dev/dont-let-sms-spam-phish-you-8b7033dfc67a</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Wed, 09 Aug 2017 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Phishing">Phishing</a> scams aren’t anything new. If you’ve lived through the early days of the interwebs, you can probably recall a couple of run-ins with a phony duplicate of your favorite website.</p>
<p>Most times sketchy emails with arbitrary, suspicious links can be spotted from a mile away. However, now that we’re all device connected, mobile phones have been the target of many attacks. And unfortunately, mobile apps can be less than forward about what site you’re currently viewing.</p>
<p>Recently, I received a random text that my Bank of America (BofA as so aptly provided in the text) account had been locked.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/a789322c-6741-4863-aa3f-460ac87112a5.png" alt="" /></p>
<p>*Use asterisks to denote importance y0!*</p>
<p>To anyone with a Bank of America account, this could certainly be alarming. I however, do not possesses a BofA account… so… good game spammer?</p>
<p>Now if you can’t control yourself after receiving an alert like this, do yourself a favor; <em><strong>Go to the verified site rather than using the spammy link provided!</strong></em></p>
<p>But to satisfy my curiosity, I decided to click the link...</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/b7fbec67-2345-4b4a-ae8d-0cda7eb61726.png" alt="" /></p>
<p>Hey, that looks like Bank of America’s desktop site! Must be legit!</p>
<p>Certainly looks like what we’d expect from an average Bank of America site but, we still don’t know what web address we’re visiting.</p>
<p><em>Sidenote: after visiting the Bank of America site later, their mobile version looks nothing like this! Shame on this h4x0r for not viewport adapting their phishing site!</em></p>
<p>If you notice, our built-in browser doesn’t show the URL web address, just the <code>&lt;title&gt;</code> tag — which is controlled by our malicious h4x0r.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/762509d0-ae8f-4c37-b2a5-a939357a6b4c.png" alt="" /></p>
<p>Thankfully, we can tap those 3 little dots to the right for “Open in Internet” which gives us the real address.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/5803edb5-ffba-4cb6-bda9-b2fef7f49d02.png" alt="" /></p>
<p>Unless there’s a new Brazilian branch of Bank of America <a href="http://whois.domaintools.com/acajardcorretoradeseg.com.br">owned by Anderson Ferro</a>, don’t go entering your account credentials unless you know the site you’re visiting!</p>
<p>Be smart when clicking things!</p>
]]></content:encoded></item><item><title><![CDATA[Debugging Mobile Apps with mitmproxy]]></title><description><![CDATA[Ever wonder exactly what network connections your favorite mobile app is making? In this small walkthrough, we’ll use mitmproxy to gain insight into how…]]></description><link>https://rambling.hashnode.dev/debugging-mobile-apps-with-mitmproxy-4596e56b3da2</link><guid isPermaLink="true">https://rambling.hashnode.dev/debugging-mobile-apps-with-mitmproxy-4596e56b3da2</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 06 Aug 2017 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Ever wonder <em>exactly</em> what network connections your favorite mobile app is making? In this small walkthrough, we’ll use mitmproxy to gain insight into how some of our favorite mobile apps work.</p>
<p>Before getting started though, it’s worth mentioning that there are plenty of other tools that allow use to do the same; such as: <a href="http://www.telerik.com/fiddler">Fiddler</a> and <a href="https://www.charlesproxy.com/">Charles Proxy</a>. I prefer mitmproxy for it’s simplicity. Fiddler is a close second as it provides far more rich network details (and Websocket frame inspection 👍)</p>
<h3><strong>Prerequisites</strong>:</h3>
<ul>
<li>A mobile device connected to same network as your proxy PC</li>
<li>mitmproxy — <a href="https://mitmproxy.org/">https://mitmproxy.org/</a></li>
</ul>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/22e42ad7-aef8-49a4-8431-fdc5ce17fb36.png" alt="" /></p>
<h3>mitmproxy</h3>
<p>This is what we’ll use to proxy information from our mobile device to our PC. mitmproxy is available for most devices: iPhone, Android and Windows phone on macOS, Windows and linux. For our example, we’ll be using an Android device on macOS Sierra.</p>
<h4><strong>Installation</strong>:</h4>
<pre><code>$ brew install mitmproxy
</code></pre>
<h4><strong>Usage</strong>:</h4>
<pre><code>$ mitmproxy
</code></pre>
<p>On mac, it couldn’t be much simpler to install and use. However, on Windows, you’ll need to use the <a href="http://docs.mitmproxy.org/en/stable/mitmweb.html">mitmweb</a> client.</p>
<p>Once you invoke <code>mitmproxy</code>, you should see a black screen in your terminal like the image above.</p>
<p>In order to use this proxy though, we’ll need to make a small configuration change on our mobile device. But before doing so, we’ll want to obtain our PC’s IP address by using <code>ifconfig</code> (or <code>ipconfig</code> for Windows).</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/f7850eae-2045-414b-b37d-b9b75ac91df2.png" alt="" /></p>
<p>As highlighted above, our (internal) network IP is <code>192.168.1.13</code>.</p>
<h3>Mobile Proxy Configuration</h3>
<p>Once you have mitmproxy installed and listening for activity, we can then configure our Mobile device to use the proxy.</p>
<p>For Android, you’ll want to go into your Mobile Device’s Network Connection settings and long press the network in which you wish to use your proxy on (the same one your PC is connected to).</p>
<p>Ours is <code>FBI Counter Intel</code> 😃</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/5403926a-980c-4d4f-9a1e-4116e830f1c0.png" alt="" /></p>
<p>Once configuring your network, you’ll need to go down to Advanced Settings in order to configure the proxy.</p>
<p>Here, we use the same IP address we obtained earlier along with <code>8080</code> (mitmproxy’s default) for the port.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/02d862ba-76e0-4fae-9473-d0674f3c9971.png" alt="" /></p>
<h3>Installing mitmproxy certificate</h3>
<p>Visit: <a href="http://mitm.it">http://mitm.it</a></p>
<p>If all went well up until this point, you should be able to hit the URL above and download the certificate (which allows the proxy to sniff data).</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/dc93041b-75ae-4104-84ff-c968c2aedab5.png" alt="" /></p>
<p>If you’re able to hit mitm.it from your mobile device (which is a non-existing/proxy specific url), you should now be able to see traffic starting to appear in your terminal.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/00c5629d-65f7-41ce-9d71-c35141cc6008.png" alt="" /></p>
<p>To leverage the mitmproxy output, you can use directional keys (mainly, up and down) to cycle through requests and a few other shortcuts to navigate further.</p>
<ul>
<li>If you hit ENTER on any request, you can see more information such as request and response headers, etc.</li>
<li>You can use TAB to switch between Request, Response and Detail tabs.</li>
<li>Hit q to go back to the request list.</li>
</ul>
<p>So if we wanted to review more information on the initial mitm.it request our Android device made, we could hit ENTER and see the following.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/f71a64d7-25c3-4c78-97ca-2a716a2a37c6.png" alt="" /></p>
<h3>Mobile Application Debugging</h3>
<p>From here, the sky is the limit (with a few exceptions). Some applications are clever enough to detect when a proxy is used — and just refuse to work under those conditions. That said, most applications work going this route.</p>
<p>Let’s take a quick look at <a href="https://play.google.com/store/apps/details?id=com.kiloo.subwaysurf&amp;hl=en">Kiloo’s Subway Surfers</a>. You may remember this game from not too distant past. At 24 million installs via the Google Play store, this game is still running strong (get it?) and is definitely one of my favorites.</p>
<p>For the record, it’s probably worth mentioning that this likely breaks their EULA. Eh, I paid for Double Coins power up on iOS and was unable to port that feature over when switching to Android. For that, they get to be the subject of this demo — plus, it really is a fun game if you haven’t tried it.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/843dd048-f21e-4c94-827c-f1f34974da9b.png" alt="" /></p>
<p>Simply opening the Subway Surfers app, creates a lot of buzz within our mitmproxy terminal.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/0469a1ce-f2a9-4c11-bb4a-ace74f30287c.png" alt="" /></p>
<p>Also, if you’ve been using the mitmweb app, your output should look similar to the following:</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/00caf8d3-254e-45d1-9fec-c49e46c911d3.png" alt="" /></p>
<p>And just like before, we can hit ENTER to see more details.</p>
<p>An interesting sidenote, this is a great way to understand how a particular application is built. By simply examining the request headers, we can see that this is a <a href="https://unity3d.com/">Unity</a> powered game on version <code>5.5.1f1</code></p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/bd3ada7b-9a55-455c-a2a3-23ab74ec5c87.png" alt="" /></p>
<p>Diving further, one popular quest within the game is the Daily Challenge in which, players are required to collect Letters that spell a given word.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/82cb1b65-4353-440c-8cc4-c545805f3c75.png" alt="" /></p>
<p>And by looking at the request data, we can see where this Word of the day comes from — and even more detail; they’re using <a href="https://httpd.apache.org/">Apache</a> and <a href="http://php.net/manual/en/intro-whatis.php">PHP</a> 😅</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/121f70ea-be5f-41d2-892d-54a8f677dd49.png" alt="" /></p>
<p>Hope this helps!</p>
<p>Happy debugging!</p>
]]></content:encoded></item><item><title><![CDATA[JSON Web Tokens (JWT) with Restify]]></title><description><![CDATA[This is a very simple example of signing and verifying JSON Web Tokens using Restify. If you’d like more information on either subject, check out the…]]></description><link>https://rambling.hashnode.dev/json-web-tokens-jwt-with-restify-bfe5c4907e3c</link><guid isPermaLink="true">https://rambling.hashnode.dev/json-web-tokens-jwt-with-restify-bfe5c4907e3c</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 18 Jun 2017 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/a880441c-dd64-4110-b9af-018afddfddb2.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a very simple example of signing and verifying JSON Web Tokens using Restify. If you’d like more information on either subject, check out the following links:</p>
<ul>
<li><a href="http://techblog.netflix.com/2014/11/nodejs-in-flames.html">http://techblog.netflix.com/2014/11/nodejs-in-flames.html</a></li>
<li><a href="https://jwt.io/introduction/">https://jwt.io/introduction/</a></li>
</ul>
<p><a href="https://jwt.io/introduction/">https://jwt.io/introduction/</a></p>
<h3>Getting Started</h3>
<p>First, we’ll need to install a few dependencies</p>
<pre><code class="language-plaintext">$ npm i --save restify restify-jwt-community jsonwebtoken
</code></pre>
<ul>
<li><a href="http://restify.com/"><code>restify</code></a> will act as our api server (developed by <a href="https://github.com/orgs/restify/people">Netflix</a>)</li>
<li><a href="https://github.com/frbuceta/restify-jwt-community"><code>retify-jwt-community</code></a> is a middleware we'll use to validate json web tokens</li>
<li><a href="https://github.com/auth0/node-jsonwebtoken"><code>jsonwebtoken</code></a> is a library we'll use to create and sign json web tokens</li>
</ul>
<p><em>As a sidenote: we could just as easily accomplish this without the use of extra middleware. However,</em> <code>restify-jwt-community</code> <em>(forked from</em> <a href="https://github.com/auth0/express-jwt"><code>auth0/express-jwt</code></a><em>), provides us with a simple interface and drops a</em> <code>req.user</code> <em>property for quick reference.</em></p>
<p>Second, we’ll start with a very basic restify server:</p>
<pre><code class="language-javascript">"use strict";

const restify = require('restify');  
const config = require('./config');
const app = restify.createServer();

app.use(restify.plugins.queryParser());  
app.use(restify.plugins.bodyParser());

app.listen(8080, () =&gt; {  
    console.log('%s listening at %s', app.name, app.url);
});
</code></pre>
<p>Nothing too out of the ordinary here. We include a local <code>config.json</code> module and for now, this can just be a simple object. The important thing is to define a secret which can be used throughout your application. Whether this comes from a config file or <a href="https://nodejs.org/api/process.html#process_process_env">environment variable</a> is up to you 😊</p>
<pre><code class="language-javascript">{
  "jwt": {
    "secret": "&amp;@$!changeme!$@&amp;"
  }
}
</code></pre>
<p>The <code>secret</code> above will be used to sign and validate json web tokens throughout our app, so you'll want to be sure to make it unique. However, without any endpoints, this server is a bit useless in its current state.</p>
<h3>Moving right along</h3>
<p>Let’s assume we have some simple login system that returns very generic information about the supplied credentials:</p>
<pre><code class="language-javascript">"use strict";

exports.authenticate = (username, password) =&gt; {
    return Promise.resolve({ uid: 1, name: 'Sean', admin: false });
};

/*
exports.authenticate = (username, password) =&gt; {  
  return new Promise((resolve, reject) =&gt; {
    db.findOne({username, password}, (err, data) =&gt; {
      if (err) return reject(err);
      resolve(data); // {uid: 1, name: Sean, admin: false}
    });
  });
};
*/
</code></pre>
<p>Obviously, we’re mocking a response above but, any real implementation would work here — like the piece commented out. As such, we can add the following to our <code>server.js</code> (save for further input validaton).</p>
<pre><code class="language-javascript">const user = require('./lib/user');

app.post('/auth', (req, res, next) =&gt; {  
  let {username, password} = req.body;
  user.authenticate(username, password).then(data =&gt; {
    res.send(data);
  })
});
</code></pre>
<p>This allows us to (insecurely) POST to an /auth route with some credentials to get our mocked response — probably less than surprising at this point.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/f3782050-066a-4975-8fc7-471fd9c02ba8.png" alt="" style="display:block;margin:0 auto" />

<h3>Sign, Deliver and Validate JWT</h3>
<p>Now let’s secure any and all of our endpoints (except for /auth). Then we’ll need to update our /auth handler to instead reply with a JWT:</p>
<pre><code class="language-javascript">const config = require('./config');
const rjwt = require('restify-jwt-community');
const jwt = require('jsonwebtoken');

// using restify-jwt to lock down everything except /auth
app.use(rjwt(config.jwt).unless({
    path: ['/auth']
}));

// using the `req.user` object provided by restify-jwt
app.get('/user', (req, res, next) =&gt; {
    res.send(req.user);
});

app.post('/auth', (req, res, next) =&gt; {
    let { username, password } = req.body;
    user.authenticate(username, password).then(data =&gt; {
        // creating jsonwebtoken using the secret from config.json
        let token = jwt.sign(data, config.jwt.secret, {
            expiresIn: '15m' // token expires in 15 minutes
        });

        // retrieve issue and expiration times
        let { iat, exp } = jwt.decode(token);
        res.send({ iat, exp, token });
    })
});
</code></pre>
<p>Our reply now gives us a JSON Web Token and details about when it was issued at (iat) and the time it expires (exp). At this point, let’s hit our /auth endpoint again and see the altered response.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/a866c0c7-1ff1-4faa-9eeb-5cbad6457ee9.png" alt="" style="display:block;margin:0 auto" />

<p>In our example, the token will automatically expire in 15 minutes — consumers will then need to either re-authenticate our look at <a href="https://www.npmjs.com/package/jsonwebtoken#refreshing-jwts">refreshing the token</a>.</p>
<p>Now we can start using our /user endpoint. By default, it will respond with a <code>401 Unauthorized</code> if no <code>Authorization</code> header is passed in the request. The Auth header value should be formatted as <code>Bearer [token]</code> or <code>Jwt [token]</code> according to the <a href="https://github.com/frbuceta/restify-jwt-community/blob/master/test/jwt.test.js#L61">tests</a>.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/728a7b43-9bde-4920-90b6-caa2519168a0.png" alt="" style="display:block;margin:0 auto" />

<p>If you’d like to view the full example:</p>
<ul>
<li><a href="https://github.com/sean3z/restify-jsonwebtoken-example">https://github.com/sean3z/restify-jsonwebtoken-example</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[REST API: Node vs Rust]]></title><description><![CDATA[With all the hype surrounding Rust, I’ve decided to take a closer look. So I spent about an hour or so looking over the Rust Docs and admittingly, it looks…]]></description><link>https://rambling.hashnode.dev/rest-api-node-vs-rust-c75aa8c96343</link><guid isPermaLink="true">https://rambling.hashnode.dev/rest-api-node-vs-rust-c75aa8c96343</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Tue, 07 Feb 2017 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/a945f381-6d6e-4226-896b-778ba8d057cb.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/b6e6b80b-8f6d-4334-ba9c-4e5484adf048.jpg" alt="" /></p>
<p>With all the hype surrounding <a href="https://www.rust-lang.org/en-US/">Rust</a>, I’ve decided to take a closer look. So I spent about an hour or so looking over the <a href="https://doc.rust-lang.org/book/syntax-and-semantics.html">Rust Docs</a> and admittingly, it looks like a really fun language.</p>
<p>However, I wanted to see how it’d stack up against my current favorite web layer Node.js using the <a href="http://seanwragg.com/2017/02/06/rest-api-node-vs-rust/%28https://github.com/restify/node-restify%29">Restify</a> framework. To do this, I’ve decided to use <a href="https://github.com/SergioBenitez/Rocket">Rocket</a> as my Rust web framework. I did notice <a href="http://ironframework.io/">Iron</a> and several other Rust web frameworks but, I really liked the simplicity of the Rocket interface. I think <a href="http://nickel.rs/">nickel</a> would have been my next choice.</p>
<p>Below we have a snippet for Rocket and another for Restify.</p>
<h3>Rust (via Rocket)</h3>
<p>Compiled via <code>cargo build --release</code> using <code>rustup default nightly</code> (as required by Rocket). <code>rocket</code> and <code>rocket_codegen</code> pinned at version <code>0.2.0</code>.</p>
<p>It’s also worth pointing out that Rocket relies on a <code>ROCKET_ENV</code> environment variable which can be found under the <a href="https://rocket.rs/guide/configuration/#environment">Environment</a> section of the docs (thanks <a href="https://github.com/SergioBenitez">@SergioB</a>!) and can be set to either <code>development</code>, <code>staging</code> or <code>production</code>. It's important to set this to <code>production</code> otherwise Rocket will run in development mode by default regardless of using the <code>--release</code> flag in cargo.</p>
<pre><code>rustc 1.17.0-nightly (ea7a6486a 2017-02-04)  
cargo-0.18.0-nightly (d710222 2017-02-04)
</code></pre>
<h3>Node (via Restify)</h3>
<p>Run via <code>node src/server.js</code> - nothing really special here. <code>restify</code> pinned at version <code>4.0.3</code></p>
<pre><code>node v6.9.5
npm 3.10.30
</code></pre>
<h3>Developer Environment</h3>
<p>Coming from a primarily Javascript heavy ecosystem (npm), I felt right at home with Rust. <a href="http://doc.crates.io/guide.html"><code>Cargo</code></a> feels a lot like a merge between npm and any standard task runner (similar to Grunt or Gulp). Packages are called <a href="https://crates.io/">crates</a>. Cargo creates a <code>Cargo.toml</code> similar to <code>package.json</code> except in ini format.</p>
<p>There’s a lot of parallels to draw upon right out of the box. It didn’t feel overly complicated like getting Java (via JAX-RS) up and running the first time.</p>
<p>After painlessly installing the necessary components, I was able to jump right into code without issue. This is one of my favorite things about Javascript — so I’m happy this type of quick engagement has been replicated.</p>
<p>I think this results in a tie in initial setup. Node may have the edge though with the larger community.</p>
<h3>Route Interface</h3>
<p>I really enjoy the Rocket interface so far. However, I am biased towards the annotation syntax and wish more Node libraries would adopt it (now that we have decorators). I haven’t gone in depth at dealing with CORS, Cookies, etc. with Rocket yet but, I’m hopeful since the <a href="https://api.rocket.rs/rocket/">docs</a> seem well written.</p>
<p>Perhaps, one of the best features is the static typing as used for route params. If the type doesn’t match, the request is <a href="https://rocket.rs/guide/requests/#forwarding">forwarded</a> to the next matching route or a 404 is served.</p>
<p>Now with Restify, we can supply some regex for dynamic route validation but, while convenient, this truly is an eye-sore and can become difficult to maintain. And obviously, this does not enforce type casting upon <code>req.params</code> (as they're all treated as strings).</p>
<p>I think Rust (via Rocket) has the upper hand here.</p>
<h3>Memory Consumption</h3>
<p>For starters, given that Rust is a systems programming language, this should come as no surprise that it idles at a much lower rate than Node. However, I need to investigate better ways to monitor memory locally and look at this a bit more closely under heavy traffic. For now I’m just using <code>top -pid</code></p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/343c83cf-24cd-418b-9584-f038a9378ec8.png" alt="" /></p>
<p>Running Rust (Rocket), idle @ &lt; 1MB</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/4cb92f2e-f1d8-4642-851b-66880881148b.png" alt="" /></p>
<p>Running Node (restify), idle @ 19MB</p>
<p>With Restify at <strong>19MB</strong> and Rocket just over <strong>1MB</strong>, if I were to guess, I’d assume Rust would win here in the long run.</p>
<h3>Requests per Second</h3>
<p>For this, I used originally used <a href="http://httpd.apache.org/docs/current/programs/ab.html">ApacheBench</a> but, found it to produce inconsistent and (oddly) less performant results. I’ve instead switched to <a href="https://github.com/wg/wrk">wrk</a> which seems to perform more reliably.</p>
<pre><code>wrk -d1m http://localhost:8080/
</code></pre>
<p>The results however, were staggering to say the least for both test suites!</p>
<p><a href="https://datawrapper.dwcdn.net/ZrTz7/1/">Embedded content</a></p>
<p>Restify was able to reply steadily at nearly <strong>8,000</strong> RPS. Rocket however, was able to churn out a fierce <strong>72,000</strong> RPS!!</p>
<p>I think Rust (and Rocket) wins this category</p>
<h4>wrk Benchmark Raw Results</h4>
<ul>
<li>Results for <a href="https://gist.github.com/sean3z/aa88bce0816878afb651277547b51f58">Rust (via Rocket)</a></li>
<li>Results for <a href="https://gist.github.com/sean3z/9255a421df3389c728d837bd108484a9">Node.js (via Restify)</a></li>
</ul>
<h4>Original AB Benchmark Raw Results</h4>
<ul>
<li>Results for <a href="https://gist.github.com/sean3z/e06cfd0ebff0231771e8173f44eb5177">Rust (via Rocket)</a> (~9,300 RPS)</li>
<li>Results for <a href="https://gist.github.com/sean3z/b6426ed9dae521c4b56948ce2c6062b1">Node.js (via Restify)</a> (~2,800 RPS)</li>
</ul>
<p><em>Originally published at</em> <a href="http://seanwragg.com/2017/02/06/rest-api-node-vs-rust/"><em>seanwragg.com</em></a> <em>on February 7, 2017.</em></p>
]]></content:encoded></item><item><title><![CDATA[Hulu’s ‘Shut Eye’ — Thoughts]]></title><description><![CDATA[Let me start by stating, I (for the most part) actually enjoyed watching this series as the acting was superb. Also, this rant will most certainly contain…]]></description><link>https://rambling.hashnode.dev/hulus-shut-eye-thoughts-b9a0a7f1bb80</link><guid isPermaLink="true">https://rambling.hashnode.dev/hulus-shut-eye-thoughts-b9a0a7f1bb80</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Tue, 27 Dec 2016 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/2d24883e-a6e4-48f3-9a77-413a67320676.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let me start by stating, I (for the most part) actually enjoyed watching this series as the acting was superb. Also, this rant will most certainly <em><strong>contain spoilers</strong></em> (duh).</p>
<p>If you haven’t already, checkout Hulu’s Original Series <a href="http://www.hulu.com/shut-eye">Shut Eye</a> starring Jeffrey Donovan. Admittingly, as a Burn Notice fan, this was the only reason I was even remotely interested in this series.</p>
<blockquote>
<p><em>SHUT EYE takes a darkly comedic look at the world of Los Angeles storefront psychics and the organized crime syndicate that runs them.</em></p>
<p><em>— Hulu Press</em></p>
</blockquote>
<p>Personally, I would have never been drawn to the plot alone but, unlike seemingly most criticism will admit, this show does have its moments.</p>
<p>The story starts with Charlie Haverford (Jeffrey Donovan) — a failed magician turned (for-profit) fortune teller, working for a Romani kingpin boss. Throughout the series though, we discover that Charlie has a wife that is less than faithful (which he seems to begrudgingly accept), a daughter from a previous relationship (whom is just somewhat of a plot device), and a son who is desperately seeking affection from some rando school girl.</p>
<p>The series follows Charlie after a vicious beat down and blow to the head from a client’s (angry) boyfriend. After which, he begins to (wait for the irony…) have visions of the future.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/1ba6a22e-a8b9-4475-b912-522335f59e54.gif" alt="" style="display:block;margin:0 auto" />

<p>My gripe here aren’t the visions themselves. In fact, they’re handled quite well and can occasionally have you guessing whether what we’ve witnessed is real or only exists in Charlie’s mind.</p>
<p>Anyway, there’s plenty of topics to dive into but all in all, this series was an enjoyable watch and I’d recommend it if you can get past some lack of closure and poor setup for another season.</p>
<p>Which brings me to the issues with this series finale:</p>
<h3>More Shut Eye after Season 1?</h3>
<p>After 10 episodes, it’s difficult to find reason to tune in again. While the final episode does it’s part to throw in additional plot devices, they seemed like afterthoughts rather than major game changing reveals.</p>
<h3>Eduardo and Fonso are BFFs</h3>
<p>The ending thought of Eduardo (David Zayas) and Fonso (Angus Sampson) working together (since we’re lead to believe they’re conspiring against Charlie), simply doesn’t make sense. I’m sure someone would argue, “well, that’s why you need to watch season 2” — but unfortunately, it’s just not a big enough hook for this viewer’s attention.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/16f596b2-3a10-40c0-9685-17573e35a1e7.png" alt="" style="display:block;margin:0 auto" />

<p><em>“What now?” — Eduardo</em></p>
<p>I mean, let’s agree that this can only be a new found partnership between the two (anything else would require far too much disbelief). Outside of both being scandalous crime bosses, their only common thread (thusfar) is having been duped by Charlie. And despite a few inconveniences, Charlie seemed to genuinely want to help Eduardo (as a mutual benefit of course).</p>
<p>In fact, one could argue that, outside of the obvious love interest with Dr. Nora White (Susan Misner), Eduardo may have been Charlie’s only friend.</p>
<p>Inversely, Eduardo wants (needs?) Charlie’s spidey-sense. So even though Charlie “cost” him 1 million dollars, the skill itself has been proven. And given what we’ve seen of Eduardo’s character, I doubt he will quickly forget Charlie saving his son or correctly predicting the fire death.</p>
<p>The only direction, I think the story can go from here: Eduardo is only working with Fonso in furtherance of his scheme with Charlie.</p>
<p>This brings me to my next concern — Charlie’s scam and the nail found in Charlie’s bedroom.</p>
<h3>Not the happy ending Charlie was expecting</h3>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/668177ce-9fc6-4426-a9a5-5a0d396121ca.png" alt="" style="display:block;margin:0 auto" />

<p>Now it’s easy to draw the parallels that bring Fonzo’s Jesus story full circle but, let’s dissect the final con a bit.</p>
<p>It’s made clear that Charlie is less than successful on most deceitful endeavors. Failed magician, caught trying to scam a gypsy as a fortune teller (which leads to his working for Fonzo?), and even after getting exceptionally close, unable to (initially) complete the con on Nadine Davies (Mel Harris).</p>
<p>So it’s difficult to imagine that Charlie would be able to pull off the perfect heist regardless of help. And this particular scheme saw the death of Fonzo’s biggest rival White Tony (Zak Santiago), arrest of Fonzo’s mother Rita (Isabella Rossellini), the break up of a wedding between Fonzo’s daughter Drina Marks (Havana Guppy) and Little Tony (Patrick Lubczyk), and Charlie regaining control of the money stolen from Nadine Davies.</p>
<p>Given the Fonso/Eduardo ending and the nail found in Charlie’s room, it’s safe to assume Fonso is well aware of Charlie’s original plan (to rift the Romani family). And of course, all of Fonso’s benefits are of his own opportunity seizing but, without Charlie’s scheme none would have happened! So Fonso and Charlie should be best pals at this point!</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/a26e1f32-b3f1-431a-9642-c7f02e491674.jpg" alt="" style="display:block;margin:0 auto" />

<p>Other than the money, it’s difficult to see a scenario where Fonso isn’t the happiest guy out of the whole series at this point — which neutralizes Charlie’s biggest Season 2 adversaries.</p>
<p><em>Originally published at</em> <a href="http://seanwragg.com/2016/12/26/hulu-shut-eye-thoughts/"><em>seanwragg.com</em></a> <em>on December 27, 2016.</em></p>
]]></content:encoded></item><item><title><![CDATA[Quick thoughts: Traffic Control Systems]]></title><description><![CDATA[I’m sure we’ve all experienced that moment in traffic: sitting in an intersection, waiting for the light to go green. Then, probably yelling at the…]]></description><link>https://rambling.hashnode.dev/quick-thought-traffic-control-systems-293a0ab4ead2</link><guid isPermaLink="true">https://rambling.hashnode.dev/quick-thought-traffic-control-systems-293a0ab4ead2</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 18 Sep 2016 00:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6aefcf97a529a56101dcc7c8/95eab2a9-9e9b-4e55-ad04-d3ddddacc752.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’m sure we’ve all experienced that moment in traffic: sitting in an intersection, waiting for the light to go green. Then, probably yelling at the immediate vehicle in front of you for sleeping through the light when it finally changes in your favor.</p>
<p><em>If you’ve experienced this more than you’d like, you’re in luck: MIT predicts that</em> <a href="http://www.computerworld.com/article/3045942/car-tech/mit-hopes-to-eliminate-traffic-lights.html"><em>Red lights will probably become a thing of the past</em></a><em>.</em></p>
<p>However, have you ever thought about how a traffic intersection works? It may be more complex than one would initially think.</p>
<p><a href="https://giphy.com/embed/3og0ITtqW8fWsOGXbq/twitter/iframe">Embedded content</a></p>
<p>Citybound SIM</p>
<h3>Obligatory History</h3>
<blockquote>
<p>The world’s first, manually operated gas-lit traffic signal was short lived. Installed in London in December 1868, it exploded less than a month later, injuring its policeman operator. Traffic control started to seem necessary in the late 1890s and Earnest Sirrine from Chicago patented the first automated traffic control system in 1910. It used the words “STOP” and “PROCEED”, although neither word lit up.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/e37de11d-9bf3-4e0d-a66a-008115f3769c.png" alt="" style="display:block;margin:0 auto" />

<p>Pasadena Traffic Signal 1928</p>
<h3>Signal Rules</h3>
<p>Alright, so let’s establish some ground rules for most basic Signal Lights — as they can vary throughout the world.</p>
<h4>Red</h4>
<ul>
<li>Vehicle must come to a complete stop</li>
<li>Vehicles can <a href="https://en.wikipedia.org/wiki/Turn_on_red">“turn right on red”</a> but, them system doesn’t need to explicitly know about it.</li>
</ul>
<h4>Yellow</h4>
<ul>
<li>Vehicle may stop if able to do so safely</li>
<li>Signal light will soon be Red</li>
</ul>
<h4>Green</h4>
<ul>
<li>Vehicle may proceed if intersection is clear</li>
</ul>
<p>Now obviously, this becomes more complicated once you introduce Turn Signals for traffic turning either left or right.</p>
<h3>Traffic Control Approach</h3>
<p>These days there’s generally a fewways to go about traffic control flow <br />(if we eliminate the possibility of vehicles communicating with one another):</p>
<h4><a href="https://en.wikipedia.org/wiki/Traffic_light_control_and_coordination#Fixed_time_control">Fixed time control</a></h4>
<ul>
<li>Lights are on hard timers between 30 and 120 seconds.</li>
</ul>
<h4><a href="https://en.wikipedia.org/wiki/Traffic_light_control_and_coordination#Dynamic_control">Dynamic Control</a></h4>
<ul>
<li>Lights change in favor of vehicles present using various means of detection</li>
</ul>
<h4><a href="https://en.wikipedia.org/wiki/Traffic_light_control_and_coordination#Coordinated_control">Coordinated Control</a></h4>
<ul>
<li>Attempting to give drivers a long string of green lights in succession</li>
</ul>
<h4><a href="https://en.wikipedia.org/wiki/Adaptive_traffic_control">Adaptive Control</a></h4>
<ul>
<li>Automatically adjust light timing based on how long vehicles have been present</li>
</ul>
<p>Each having their own advantages (and disadvantages). However, there’s also several other factors that most system additionally features</p>
<h4>Emergency vehicles</h4>
<ul>
<li>Need the ability to stop all traffic at an intersection.</li>
</ul>
<h4>Non-motorized user detection</h4>
<ul>
<li>Pedestrians attempting to cross an intersection will affect which lanes can move at a given time.</li>
</ul>
<h4>Part-time operation</h4>
<ul>
<li>Disabling traffic lights at night or when traffic is low</li>
</ul>
<h4>Bus and Transportation Priority</h4>
<ul>
<li>Some traffic signals are activated to coincide with the arrival of a bus or tram.</li>
</ul>
<h4>Railroad preemption</h4>
<ul>
<li>Some traffic signals are activated to coincide with the approach of a train</li>
</ul>
<h4>Manual override</h4>
<ul>
<li>Most systems can be manually operated using a local junction box</li>
</ul>
<p><em>Originally published at</em> <a href="http://seanwragg.com/2016/09/18/traffic-control-system-part-1/"><em>seanwragg.com</em></a> <em>on September 18, 2016.</em></p>
]]></content:encoded></item><item><title><![CDATA[PHP: A case for Zephir]]></title><description><![CDATA[Zephir is an open source, high-level language designed to ease the creation and maintainability of extensions for PHP, with a focus on type and memory…]]></description><link>https://rambling.hashnode.dev/php-a-case-for-zephir-1d9df68f8aa4</link><guid isPermaLink="true">https://rambling.hashnode.dev/php-a-case-for-zephir-1d9df68f8aa4</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Wed, 06 Jan 2016 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Zephir is an open source, high-level language designed to ease the creation and maintainability of extensions for PHP, with a focus on type and memory safety.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/83d5d43c-2a3b-4ba0-b096-86bce29e0b38.jpg" alt="" /></p>
<p>(Ze)ndEngine / (P)HP / (I)nte(r)mediate</p>
<p>Zephir is a language that addresses the major needs of a PHP developer trying to write and compile code that can be executed by PHP. For all intents and purposes, it’s a transpiler that allows you to write code in a custom “Zephir” language that compiles down to C++.</p>
<h3>Installation</h3>
<p>The <a href="http://docs.zephir-lang.com/en/latest/install.html">installation docs</a> will suggest using Composer however, I’ve found it easier to compile from source.</p>
<pre><code>$ brew install re2c
$ git clone git@github.com:phalcon/zephir.git
$ cd zephir &amp;&amp; ./install -c
$ zephir help
</code></pre>
<h3>Some basics</h3>
<p>There are some basic details to remember when writing Zephir code:</p>
<ul>
<li>No opening tag/line (<code>&lt;?php</code>, <code>&lt;?</code>, etc.)</li>
<li>Defining a property value will make it immutable, define initial values in the <code>__construct</code> method if you expect values to change</li>
<li>Methods support parameter as well as return type-hinting</li>
<li>Using <code>string</code>, <code>array</code>, <code>int</code> type hints for parameters makes them immutable, use <code>var</code> if the values will change</li>
<li><a href="https://github.com/phalcon/zephir-sublime">There is a Sublime Text syntax highlighter available</a></li>
<li>String values are defined using “double-quotes”, not single-quotes</li>
<li>Defining/updating variables is done using the <code>let</code> keyword (<code>let variable = "value"</code>)</li>
<li>You cannot (currently) create classes in the <a href="http://php.net/manual/en/language.namespaces.global.php">Global Space</a></li>
</ul>
<h3>Findings</h3>
<p>In this case, a custom version of the <code>library/Zend/Registry.php</code> file was deployed.</p>
<p>The below graphic is of two <a href="https://pecl.php.net/package/xhprof">XHProf</a> snapshots taken from a <a href="https://framework.zend.com/manual/1.11/en/introduction.overview.html">Zend Framework 1</a> (ZF1) application. The first is with our custom Zephir <code>Zend\Registry</code>; the second is of the existing stock PHP ZF1 <code>Zend_Registry</code>.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/e2aaed1e-84f2-45e6-a5f9-82e598f94b38.png" alt="" /></p>
<p>Perhaps the most important stat to observe is <code>Incl. Wall Time (microsec)</code>. At ~7k calls, the stock <code>Zend_Registry</code> takes ~197 milliseconds. Our custom <code>Zend\Registry</code> reduced the PHP time spent in retrieving registry items from to 95ms. As expected, the CPU load is also reduced by half.</p>
<p>Our Zephir equivalent executes <strong>53% faster</strong> than the stock <code>Zend_Registry</code>.</p>
<h3>Resources</h3>
<ul>
<li><a href="https://github.com/phalcon/zephir">https://github.com/phalcon/zephir</a></li>
<li><a href="http://zephir-lang.com/">http://zephir-lang.com/</a></li>
<li><a href="https://github.com/sean3z/zendframework-zephir">https://github.com/sean3z/zendframework-zephir</a></li>
<li><a href="http://docs.zephir-lang.com/en/latest/install.html">http://docs.zephir-lang.com/en/latest/install.html</a></li>
<li><a href="http://www.sitepoint.com/zephir-build-php-extensions-without-knowing-c/">http://www.sitepoint.com/zephir-build-php-extensions-without-knowing-c/</a></li>
</ul>
<p><em>Originally published at</em> <a href="http://seanwragg.com/2016/01/06/php-a-case-for-zephir/"><em>seanwragg.com</em></a> <em>on January 6, 2016.</em></p>
]]></content:encoded></item><item><title><![CDATA[Express route param regex validation]]></title><description><![CDATA[Recently, I came across some confusion in the Express 4.x API documentation regarding how to use regex to validation route parameters. It seems there’s…]]></description><link>https://rambling.hashnode.dev/express-route-param-regex-validation-de3790d110c3</link><guid isPermaLink="true">https://rambling.hashnode.dev/express-route-param-regex-validation-de3790d110c3</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Tue, 26 May 2015 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>Recently, I came across some confusion in the <a href="http://expressjs.com/4x/api.html">Express 4.x API</a> documentation regarding how to use regex to validation route parameters. It seems there’s been an update and the method to accomplish this differs from version <code>4.11</code> and <code>4.12</code>.</p>
<img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/b8a35112-3076-4e4c-ade5-3c1ca467e7b5.png" alt="" style="display:block;margin:0 auto" />

<p>The punchline here is that the docs actually provide all the information needed but, when you’re glancing for a quick overview in how their API works, it can be very easy to miss (and apparently I’m <a href="https://github.com/strongloop/expressjs.com/issues/388">not the only one</a> who feels that way).</p>
<p>The quick and dirty:</p>
<h3>express 4.11</h3>
<p>Essentially the following snippet would need to be run <em>prior</em> to leveraging the <a href="http://expressjs.com/4x/api.html#router.param"><code>router.param(fn)</code></a> method if you're using express <code>&lt;= 4.11</code>. (you can use <code>app</code> instead of router)</p>
<pre><code class="language-javascript">router.param(function(name, fn) {  
  if (fn instanceof RegExp) {
    return function(req, res, next, val) {
      var captures;
      if (captures = fn.exec(String(val))) {
        req.params[name] = captures;
        next();
      } else {
        next('route');
      }
    }
  }
});
</code></pre>
<p>This then grants you the ability to validate route params using the following:</p>
<pre><code class="language-javascript">// validation rule for id: should be one or more digits
router.param('id', /^\d+$/);

router.get('/user/:id', function(req, res) {  
  res.send('user ' + req.params.id);
});
</code></pre>
<h3>express 4.12</h3>
<p>If you’re using express <code>&gt;= 4.12</code> you can accomplish the same <em>without</em> the need of <code>router.param(fn)</code> using the following. In fact, the pre 4.12 example above will pop a deprecation warning.</p>
<pre><code class="language-javascript">app.get('/user/:userId([0-9]+)', fn);
</code></pre>
<p>While this is stated in the doc, it is quite easy to miss. Hopefully this helps clear things up for those that skim the docs as I did.</p>
<p><em>Originally published at</em> <a href="http://seanwragg.com/2015/05/26/express-route-param-regex-validation/"><em>seanwragg.com</em></a> <em>on May 26, 2015.</em></p>
]]></content:encoded></item><item><title><![CDATA[MPC Knight Rider KITT build]]></title><description><![CDATA[This is my second attempt at putting together any model car. My first attempt didn’t go as well as I initially expected. I’m hoping to apply the lesson’s…]]></description><link>https://rambling.hashnode.dev/mpc-knight-rider-kitt-build-64e14ee71dc</link><guid isPermaLink="true">https://rambling.hashnode.dev/mpc-knight-rider-kitt-build-64e14ee71dc</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Thu, 26 Mar 2015 00:00:00 GMT</pubDate><content:encoded><![CDATA[<p>This is my second attempt at putting together any model car. <a href="http://seanwragg.com/2014/12/14/amt-1967-shelby-gt-350-build/">My first attempt</a> didn’t go as well as I initially expected. I’m hoping to apply the lesson’s learned for a better end result :)</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/a84d7443-39e7-4855-91c9-c34fdf6f783f.jpg" alt="" /></p>
<h3>Unboxing</h3>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/80806a64-ff7a-4296-98e6-28afb2e7f524.jpg" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/c6ea3714-3086-4e17-9a55-ea804aed6d72.jpg" alt="" /></p>
<h3>Painting</h3>
<p>For the seats, I used <a href="http://www.testors.com/product-catalog/testors-brands/model-master/auto-lacquer-paint/lacquer-sand-texture-coatings">Model Master’s Fabric Tan</a>; which gave them a much less plastic-y look.</p>
<p>The rip in the seat furthest to the right is unintentional. I’m not really sure how it happened but, decided to keep it since it gives the seat a more practical look after some Hoff-wear and tear.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/edb69df6-1dae-4a13-a7c3-71e3c84b4faf.jpg" alt="" /></p>
<p>I did the same with the back but, taped off everything but the seats (using masking tape). I’ve had bad experience using masking tape but, figured I could be less precise here without too much worry.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/aa242abe-c88d-4d36-aee8-829ba91bf980.jpg" alt="" /></p>
<p>Which didn’t come out too bad when the front seats were installed</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/e7ba5a7a-8b4b-4f08-b478-dae786d1416c.jpg" alt="" /></p>
<p>I installed the windows (before I realized that I wanted to paint the body); so brought out the masking tape again. Since the kit is already black, I figured I wouldn’t need a coat of primer and instead just went with spray lacquer <a href="http://www.testors.com/product-catalog/testors-brands/model-master/auto-lacquer-paint/sprays">Model Master Spray Lacquer</a> (really need to purchase an air brush).</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/695104d5-e226-454c-a4d9-03c13707485c.jpg" alt="" /></p>
<p>After spray painting (and applying top windows):</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/78fda4c6-d560-44de-93a1-fbed9e1ef292.jpg" alt="" /></p>
<p>I’m not sure how well it shows up on web but, the spray provided a much richer (more realistic looking) black.</p>
<h3>Assembly</h3>
<p>This was pretty straight forward and actually far less complex than my first model. The engine only required assembly of a few parts. The wheels are pretty static but for some reason my front passenger wheel allows for some movement.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/9a406171-f69c-493a-a1be-a502908adc84.jpg" alt="" /></p>
<p>Applying stickers:</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/93baa4c1-71db-4fc4-b461-556b0db258b0.jpg" alt="" /></p>
<h3>Delayed Completion</h3>
<p>So it’s been awhile since I’ve touched this project (months, hence the dust in the images below) but, I decided to (quickly) throw together the remaining items for completion’s sake.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/69f53601-81b0-4483-aa23-17575d9d4579.jpg" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/ff26266a-6f6f-4d34-8950-055d7b408168.jpg" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/9cfb956b-6807-4900-980c-2c400248fd78.jpg" alt="" /></p>
]]></content:encoded></item><item><title><![CDATA[AMT 1967 Shelby GT-350 build]]></title><description><![CDATA[This is an extension of my the RPF post. Many of those that have worked on model cars/trains/planes, have been doing it for years; most, starting at a…]]></description><link>https://rambling.hashnode.dev/amt-1967-shelby-gt-350-build-6e7ab6446f73</link><guid isPermaLink="true">https://rambling.hashnode.dev/amt-1967-shelby-gt-350-build-6e7ab6446f73</guid><dc:creator><![CDATA[Sean Wragg]]></dc:creator><pubDate>Sun, 14 Dec 2014 00:00:00 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p>This is an extension of my <a href="http://www.therpf.com/showthread.php?t=230485&amp;p=3601759">the RPF</a> post.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/052a92a2-dfc6-45ea-afee-fdd9c87b5bbd.jpg" alt="" /></p>
<p>Many of those that have worked on model cars/trains/planes, have been doing it for years; most, starting at a young age. Any model search on <a href="http://www.therpf.com/forumdisplay.php?f=11">the Real Prop Forum</a> will yield an impressive display from experienced modelers. Unfortunately, I’ve yet to gain that experience.</p>
<p>This my first attempt at putting together any model — it turned into an absolute disaster but, was a lot of fun!</p>
<h3>Unpackaging</h3>
<p>A couple of obligatory unpackaging shots:</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/1b420c42-14f4-4c59-bcfa-1ec9e1c68c1b.jpg" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/63101e45-f8d1-467c-b82d-eb1e37e4b933.jpg" alt="" /></p>
<h3>Painting</h3>
<p>I decided to go with a Metallic Blue with white racing stripes. I was aways a fan of this combination on the 90s Dodge Viper and figured it would work well here.</p>
<p>I started by spray painting the pieces using <a href="http://www.testors.com/product-catalog/testors-brands/testors/lacquer-paint/lacquer-sprays">Testors One Coat Lacquer Spay</a> — Metallic Blue. This was beneficial as I <em>shouldn’t</em> have to worry about a primer coat. (In the future, I will probably <a href="http://www.therpf.com/showthread.php?t=230485&amp;p=3602455&amp;viewfull=1#post3602455">move away from the one coat spray’s</a>).</p>
<p>As I’m sure you can imagine, it’s also less precise painting with a spray can (as opposed to a spray gun).</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/7fe4ac15-c72d-435b-b6d3-216b1df58026.jpg" alt="" /></p>
<p>My DSLR kind of highlights the metallic flakes more than what’s seen in natural light but, take note of the accent pieces (to the right of the hood). I’ll learn later than, I should have glued them to the car first :)</p>
<h3>Assembly</h3>
<p>This part wasn’t as difficult as I initially expected — with a little patience. The directions were straight forward and available in multiple languages. So long as you can read, this is probably the least stressful of the whole project.</p>
<p>That said, the assembly directions would have been more beneficial if the some of the sequences were changed around. However, I feel that more experienced modelers would have sniffed this out and adjusted accordingly.</p>
<p>Snapping out parts from their containers required some additional cutting/sanding to ensure some of the excess plastic wouldn’t become an issue. I assume this is a regular part of the process though</p>
<p>Oh, you’ll noticed the engine block in the image below. I painted about 5–6 pieces individually before full assembly. When trying to apply plastic glue, it would just eat the paint away. So I dipped the engine block in plastic glue to try to kill all the paint. Didn’t work as expected. This is probably the dumbest thing I’ve done. Lesson learned.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/28aa3088-19dd-407e-86c1-b401d271f7b6.jpg" alt="" /></p>
<p>I’m unsure whether it’s entirely visible here but, when spray painting — the lacquer is so thick, that it actually nuked the Shelby logo from the grill. I’ve asked for some help in my RPF post and received <a href="http://www.therpf.com/showthread.php?t=230485&amp;p=3511775&amp;viewfull=1#post3511775">some great suggestions</a>.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/baf80546-4323-43bb-ae9a-b73f5197dd79.jpg" alt="" /></p>
<p>It’s also not entirely visible in this shot but, I also messed up the front windshield. The plastic glue isn’t really the best for holding those pieces together so I opted for super glue (not a good idea). The error of my ways will be on full display in later shots.</p>
<p>Oh, and those accent pieces I mentioned earlier. Check them out (below) near the door and rear windshield. You’ll notice the top one matches a bit better (paint/color wise) than the bottom one.</p>
<p>When painting the car, I didn’t cover the bottom half nearly as thorough as the top. This is made more apparent after gluing on the accent piece. In the future, I’ll be sure to glue those on first, then paint it all together for more consistency.</p>
<p>Overall, at this point, I’m still feeling confident — a few minor errors but, I think this is very much so a salvageable project (especially with it being my first). I mean, the shot above doesn’t look like a horrible piece of work thusfar right?</p>
<p>Next, final touches?</p>
<h3>The road to disaster</h3>
<p>So I just need to assemble the front grill and rear bumper. The front grill consists of headlights (man, I love those big headlights).</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/63d2a1b8-4e6a-4551-b302-6bb2222d060e.jpg" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/5cca7458-3082-4fcf-a29d-74207f1635ae.jpg" alt="" /></p>
<p>The plastic glue wasn’t cutting it, so I switched to good ole’ super glue. Much like the spray paint on the front grill, the super glue killed some of the detail (grid) of the headlights. It’s very difficult to get the clear plastic front to sit perfectly in the bowl shaped container.</p>
<p>Oh right… the white racing stripes…</p>
<p>Yup, totally forgot about these. I should have done this at the painting stage.</p>
<p>I had to remove the rear and front windshields and grill/bumper. I used masking tape to section off where I’d like the stripes to be. I didn’t use spray paint because I wasn’t confident in my masking tape. So I manually painted using a brush (and did my best to make sure everything was even)</p>
<p>Note to self, don’t ever use masking tape. Ever.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/f73360e2-1d4d-4339-b8ca-cdf460d797c4.jpg" alt="" /><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/4085b8f6-c5c2-48c9-b368-b74d348adb1e.jpg" alt="" /></p>
<h3>Final</h3>
<p>Anyway, here is the final project.</p>
<p>When attempting to reunite the rear windshield, I guess some paint/super glue was on my finger and got applied to the window. To this day, I have no idea how to get it off. Windex does not work.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/f33ff19e-4d44-42e7-bc50-a30e28857b5c.jpg" alt="" /></p>
<p>You’ll also note that my masking tape, didn’t quite provide the affect I was looking for. Paint was still able to bleed outside of the markings.</p>
<p><img src="https://cdn.hashnode.com/uploads/posts/6aefcf97a529a56101dcc7c8/8bd56cda-ca65-43dc-8c51-d4d18be744c6.jpg" alt="" /></p>
<p><em>Originally published at</em> <a href="http://seanwragg.com/2014/12/14/amt-1967-shelby-gt-350-build/"><em>seanwragg.com</em></a> <em>on December 14, 2014.</em></p>
]]></content:encoded></item></channel></rss>