<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thomas Simmer on Medium]]></title>
        <description><![CDATA[Stories by Thomas Simmer on Medium]]></description>
        <link>https://medium.com/@thomas.simmer?source=rss-385c36f28144------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YA1F5PD3vlD4xiUrEbHMYg.jpeg</url>
            <title>Stories by Thomas Simmer on Medium</title>
            <link>https://medium.com/@thomas.simmer?source=rss-385c36f28144------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:00:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thomas.simmer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Applying with AI honestly and efficiently]]></title>
            <link>https://medium.com/@thomas.simmer/applying-with-ai-honestly-and-efficiently-57834dc644dc?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/57834dc644dc</guid>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 04:54:25 GMT</pubDate>
            <atom:updated>2026-09-23T04:54:25.794Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I built an AI assistant that applies for jobs with you, and never invents a fact about you.</em></p><p>Let me start with the honest part. Everyone uses AI to apply now. Recruiters use it to read the pile. Candidates use it to write the CV and the cover letter. That is not a scandal, it is just how hiring works now. So the only interesting question left is how to use it well.</p><p>That question is what this is about. Over one weekend, by directing DeepSeek the whole time, I built a small assistant for job hunting. You paste an offer, it scores it against your profile and your criteria, it writes a CV and a cover letter in your own template, and it drafts the answers to the application form. Apply more, apply better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_MxhEqybZPf2Oh1hfp8kg.png" /><figcaption>The board: every offer you analyzed, with its score, its verdict and where it stands</figcaption></figure><p>Two rules shaped the whole thing.</p><ul><li>It must not invent facts about you.</li><li>Its score must mean something you can check.</li></ul><p>Both look simple. Both become hard the moment a language model is in the loop. And the fix for each one turned out to be the same fix. I use it in three places.</p><h3>The one idea</h3><p>Give the model the smallest possible decision, inside a closed set. Let deterministic code do everything else.</p><p>That is the whole article, in one line. The rest is what it looks like in practice, in three places.</p><h3>First, a profile</h3><p>The three places below all rest on the same thing, your profile. So the tool starts by building it well.</p><p>You import your CV, as a PDF, a DOCX or a plain text paste. The model turns it into a structured profile under one strict rule, use only what the CV says and leave empty what it does not. Then it interviews you, one question at a time, and it asks exactly what a CV leaves out: the result behind a vague line, the scale of the thing, the decision you actually owned. Every answer goes straight into the profile, and it is checked the same way the documents are, no number you did not say, no line that does not come from what you wrote.</p><p>Ten minutes spent there is what makes every later document good. It is, I think, the biggest time saver in the whole tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slPnQ9C4DtfEFhr56iFbng.png" /><figcaption>The interview: one question at a time, on its own card</figcaption></figure><h3>1. The score</h3><p>The obvious way to score an offer is to ask the model for a number from 0 to 100. The problem is that it drifts. The same offer gets 82 on Monday and 91 on Tuesday, and nothing tells you why. And you cannot argue with 87. There is nothing to grab.</p><p>So the model does not give the number. It fills a fixed grid. Four axes, each as a small integer from 0 to 5, each with one sentence of justification. The weights and the total are in code.</p><pre>AXIS_WEIGHTS: dict[str, float] = {<br>    &quot;technical_match&quot;: 0.40,<br>    &quot;seniority_scope&quot;: 0.20,<br>    &quot;wishes&quot;: 0.25,<br>    &quot;red_flags&quot;: 0.15,<br>}</pre><pre>def build_score(grid: ScoringGrid) -&gt; Score:<br>    axes = [...]<br>    total_weight = sum(axis.weight for axis in axes) or 1.0<br>    weighted = sum(axis.score * axis.weight for axis in axes) / total_weight<br>    return Score(axes=axes, total=round(weighted / MAX_AXIS_SCORE * 100))</pre><p>Those four numbers are hardcoded, and that is on purpose. You tune your own wishes and their weights, never the grid itself. If the model picked the weights, it could quietly move the total from one run to the next, and you would never see why.</p><p>Now the model’s freedom is a few small integers instead of a number it invents from nothing. And the total is a pure function. Same grid, same total, always. When you disagree with a line, you disagree with one axis, and you can see the one sentence behind it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzgI_LOcmi7TYdZDY0grBg.png" /><figcaption>The verdict for one offer: a total computed in code, and the four axes with their justification</figcaption></figure><h3>What still belongs to the model</h3><p>The axis scores still come from the model. What is deterministic is the aggregation, not the judgement. I do not pretend otherwise. But the drift is now bounded to the step of the grid, and every stored score carries a fingerprint of its inputs, the model included. Change the model or one rule and the older scores are marked out of date, instead of being quietly mixed with the new ones.</p><h3>2. The facts</h3><p>A cover letter that invents one number is worse than no cover letter. So the prompt states the rule clearly. Use only the profile. Cite an experience for every claim.</p><p>But a prompt is a request, not a guarantee. A model can ignore it, and it often does in a subtle way.</p><p>So the same rule is checked again in code, line by line, after the draft comes back.</p><pre>invented = [n for n in numbers(line.text) if n not in profile_material]<br>if invented:<br>    flag(line, f&quot;states {&#39;, &#39;.join(invented)}, not in your profile&quot;)</pre><p>Every number in a line must already be somewhere in the profile. Every factual line must cite an experience that really exists. A skills line may not name something the candidate never listed. The name on the document must be the name in the profile.</p><p>The design rule behind it is this. Be strict about facts and relaxed about wording. The tool has no opinion on your style. It only refuses to let you say something untrue. The report is then shown next to the document, in the review screen, and you decide what to do with each line.</p><h3>What the check cannot catch</h3><p>The number check is a search for a substring. So a number that already appears somewhere else in the profile can pass in the wrong place. A claim with no number in it is judged only by its citation. It catches the worst failure, which is an invented figure, and it does not catch everything.</p><h3>3. The format</h3><p>The model writes a CV, but the CV has to come out in your template, with your fonts, your margins, your spacing.</p><p>The naive way is to read the template, note the styles, then rebuild a fresh document wearing those styles. It never matches. Word documents are a mess of local formatting, and the model’s idea of your template is only an approximation of it.</p><p>So I never rebuild anything. The user’s file stays the base, and I re-use the exact XML of the paragraph that each line was modelled on. First I keep every block with its own XML.</p><pre>blocks.append(<br>    ExtractedBlock(text=text[:MAX_TEXT], xml=paragraph._p.xml,<br>                   hint=_hint(paragraph))<br>)</pre><p>The model looks at the list of blocks and, for each one, picks a role from a closed list. A bullet, a section title, an entry title, a body line. It never sees the formatting, only the text and a short hint. Then to render, the code deep copies the XML of the block that carries the role, replaces its text, and puts it back into the document.</p><pre>element = parse_xml(xml)<br>_fill(element, line.text, line.role, link_ids)</pre><p>Fonts, colours, numbering, borders, headers and the clickable links all come from the template, because they are literally the template’s own XML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43Zk2cdiRrmPPj8289veAw.png" /><figcaption>The review screen: the editable source on one side, the rendered letter in your template on the other</figcaption></figure><h3>What it does not keep</h3><p>It works well on normal CVs and it can be wrong on strange ones.</p><h3>Why the smaller job is the right one</h3><p>When a tool writes things about you, the failures are not the failures of a chat window. A chatbot that is a bit off is mildly annoying. A document that claims a number you never earned is a real problem, in a real inbox, with a real recruiter at the other end.</p><p>So the model gets the part where judgement helps, which is reading a messy offer and putting a line in the right bucket. The code gets the part that has to be exactly right, which is the arithmetic, the facts and the layout. Each one does what it is good at, and every output can be explained.</p><h3>What I would tell someone putting a model in a product</h3><p>Ask two questions about every step.</p><p>First, what is the smallest useful decision here? Then, can I put it inside a closed set? A role from a list. A small integer on a fixed grid. Not a paragraph of free text that you will have to parse back out, because parsing it back out is where trust goes to die.</p><p>Everything the model is not deciding, keep it in code, where you can read it, test it and defend it in a meeting. That is not a limit on the model. It is what makes the model safe to use.</p><p>The code is open source, MIT licensed, and it runs on your machine. Profile, offers and documents never leave it, except the text you send to the model provider you configure.</p><p><a href="https://github.com/thomassimmer/paul">github.com/thomassimmer/paul</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57834dc644dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Cyberpunk Forensics Simulator to Teach Blue Team Thinking]]></title>
            <link>https://medium.com/@thomas.simmer/i-built-a-cyberpunk-forensics-simulator-to-teach-blue-team-thinking-e77bcbeb7b10?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/e77bcbeb7b10</guid>
            <category><![CDATA[cyberpunk]]></category>
            <category><![CDATA[forensics]]></category>
            <category><![CDATA[blue-team]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 19:53:12 GMT</pubDate>
            <atom:updated>2026-06-04T19:53:12.179Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Most security tools teach you to attack. I wanted to build something that teaches you to investigate.</strong></p><p>There’s something strange in how cybersecurity is taught.</p><p>CTFs, labs, HackTheBox, TryHackMe: they’re all great. But almost all of them focus on the <strong>offensive perspective</strong>. Find the vulnerability, exploit it, capture the flag. Which makes sense. Offensive security is concrete, gameable, and satisfying.</p><p>But the reality of most security work is different. Most people working in security spend their time on the <strong>blue team</strong>: reading logs, correlating events, writing incident reports, deciding whether a suspicious request is a false positive or the beginning of a breach. That work is harder to gamify. It’s also harder to learn.</p><p>I wanted to fix that. So I built <a href="http://thomassimmer.github.io/nightcity-tracer/">NightCity Tracer</a>: an open-source, browser-based forensics simulator set in a cyberpunk universe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfVBsNe1K02m0sPlzfSQ8A.png" /><figcaption>Welcome page</figcaption></figure><h4>What it actually is</h4><p>You play a SOC analyst in Night City. A breach happened, or is happening right now.</p><p>You get the evidence: access logs, vulnerable source code, network maps, config files, email chains, git histories, memory dumps. You investigate, reconstruct the attack, and file an incident report.</p><p>No flags. No shell to pop. Just evidence and judgment.</p><p>The game scores you on <strong>precision</strong> (did you identify the right vulnerability?), <strong>defense efficiency</strong> (did you take the right action?), and in live scenarios, <strong>speed</strong> (how much damage did you contain before it was too late?).</p><p>At the end, you get a debrief with a replay of the attacker’s exact path.</p><h4>Two radically different modes</h4><p>The most important design decision was splitting scenarios into two temporal modes.</p><p><strong>Post-mortem</strong>: the breach already happened. All evidence is present from the start. You’re reconstructing a past attack from whatever was left behind. This is closer to digital forensics: patient, methodical, no time pressure.</p><p><strong>Live</strong>: the attack is in progress. Logs arrive in real time. A countdown is ticking. A data exfiltration is on-going. You have minutes to read the code, identify the vulnerability, and submit your report before the attacker succeeds.</p><p>These two modes feel like different games. The live mode creates genuine pressure: players report making mistakes under the time constraint that they wouldn’t make with unlimited time. Which is exactly the point.</p><h4>The scenario system</h4><p>Every scenario in NightCity Tracer is a self-contained TypeScript config file. The engine reads it and assembles a completely different experience: different panels, different evidence, different scoring weights, different narrative identity.</p><p>A scenario declares:</p><p>- <strong>Which evidence panels to display</strong>: <em>log_stream</em>, <em>code_editor</em>, <em>network_map</em>, <em>db_viewer</em>, <em>terminal</em> and more. The UI builds itself dynamically from this list.<br>- <strong>The event timeline (live mode)</strong>: when each batch of logs appears, when alerts fire, when game over triggers. Payloads can be randomized to prevent memorization.<br>- <strong>Scoring dimensions and weights</strong>: a post-mortem forensics scenario weights precision heavily; a live incident scenario weights speed and defense efficiency. Each scenario defines what “a good answer” looks like.<br>- <strong>The incident report fields</strong>: a stored XSS scenario asks about the injection point and the sanitization fix. A social engineering scenario might ask for a decision (cut access now, or monitor?) rather than a technical finding.<br>- <strong>Corporate identity</strong>: each scenario belongs to a megacorp or faction with its own UI accent colors, briefing tone, and narrative voice.</p><p>This means scenarios can be radically different: not just in attack technique, but in what the player is actually being asked to do.</p><h4>The four scenarios shipping in V1</h4><p><strong>Trauma Team Dispatch: Token Forgery</strong> <em>(tutorial, post-mortem, beginner)</em><br>A medical response API was compromised via JWT algorithm confusion. You have post-breach logs and the source code. Designed to teach the investigation loop before any time pressure starts.</p><p><strong>Operation Med-Assist Override</strong> <em>(post-mortem, beginner)</em><br>An AI triage dispatch system was manipulated via prompt injection. The question isn’t just “what happened” but “what did the model do that it shouldn’t have, and why.”</p><p><strong>Watson District: Samurai on Air</strong> <em>(post-mortem, intermediate)</em><br>94 billboards. One attacker. Three seconds of footage that cost NeonGrid Systems their biggest advertiser and triggered a police investigation. Figure out how a single file upload brought down an entire district’s display network.</p><p><strong>NightOps Platform</strong> <em>(live, intermediate)</em><br>Active operator identities, drop locations, client names: everything on the platform is being exfiltrated right now. Every second you spend reading the code is a merc whose cover is blown. Stop it before the damage is irreversible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qA6mWTaaTNcfXlBZMQXd6g.png" /><figcaption>NightOps Platform scenario</figcaption></figure><h4>Why cyberpunk?</h4><p>The aesthetic isn’t decoration. It does real work.</p><p>Framing a JWT misconfiguration as “a Trauma Team dispatch system was compromised mid-emergency” changes how players engage with it. The scenario isn’t an exercise anymore: it has stakes, a world, a narrative identity.</p><p>Each faction creates a completely different feel. Arasaka scenarios feel corporate and precise, with cold system messages and red accents. A Netwatch scenario would feel more covert, like you’re working inside a surveillance apparatus. The aesthetic lets the same underlying mechanics feel like different experiences.</p><h4>The tech stack</h4><p>100% static. React 19 + TypeScript + Vite + Tailwind v4, hosted on GitHub Pages. No backend, no accounts, no analytics.</p><h4>The attacker state machine</h4><p>Live scenarios have an attacker that isn’t just a timer: it’s an actual state machine. The attacker progresses through phases (recon, exploit, exfil), each phase unlocking new log batches and changing the threat level. Players can interact: blocking an IP delays the attacker, patching a code vulnerability can stop the exfil entirely.</p><p>This creates a feedback loop that’s closer to real incident response: your actions have consequences, and the attacker progresses based on what you do or fail to do.</p><h4>What I’m looking for</h4><p>The project is open source and the scenario library is the thing that makes or breaks it.</p><p>Writing a scenario doesn’t require deep React knowledge: the config format is documented in the README with a schema walkthrough. If you know a real-world attack technique that would make a good investigation (a misconfigured S3 bucket, a malicious npm dependency, a phishing chain reconstruction, an insider threat), issues are open.</p><p>UI work, new panel types, and engine improvements are equally welcome.</p><p><strong>GitHub:</strong> <a href="https://github.com/thomassimmer/nightcity-tracer">thomassimmer/nightcity-tracer</a></p><p><strong>The Game: </strong><a href="https://thomassimmer.github.io/nightcity-tracer/">thomassimmer.github.io/nightcity-tracer/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e77bcbeb7b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CyberKey: What I learned building an embedded project coming from web development]]></title>
            <link>https://medium.com/@thomas.simmer/cyberkey-what-i-learned-building-an-embedded-project-coming-from-web-development-a11cd89e5598?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11cd89e5598</guid>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[cyberpunk]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[hardware]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Sun, 03 May 2026 14:22:00 GMT</pubDate>
            <atom:updated>2026-05-09T18:53:44.039Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a fullstack web developer with 6 years of experience. Python, Rust, JS, databases and APIs. That’s my day job. I had never touched electronics.</p><p>A few weeks ago, I decided to build CyberKey. The itch came from something boring at work: my VPN disconnects when I lock my computer, and I have to type a TOTP code several times a day. Unlock my phone, open the authenticator app, read the code, type it before it expires. Every time. CyberKey is a small device that eliminates that friction. Place the right finger on it, and the code is typed automatically over Bluetooth. No app, no phone, no copy-paste. Just a finger, and the code appears in the input field.</p><p>The project runs on an M5StickC Plus 2, an ESP32 microcontroller the size of a lighter. It’s made by M5Stack, a company that produces ESP32-based modules with a screen, a battery, and built-in connectors, as well as a range of compatible sensors and peripherals. The fingerprint sensor in CyberKey is one of theirs. It’s a reasonable entry point for software developers who don’t want to deal with breadboards and soldering. The firmware (the program that runs directly on the chip, with no operating system underneath) is written in Rust. I was heavily assisted by Claude throughout the development, and most of the work happened during my baby’s nap times, roughly two hours a day. Without that help, I couldn’t have pulled this off in a reasonable amount of time.</p><p>This is not a tutorial. It’s a synthesis of the concepts I had never encountered in six years of web development, and a walkthrough of the firmware architecture, for web developers curious about what’s on the other side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Jwpe1Ewfd6r49sW.png" /></figure><h3>The hardware: when your code talks to physics</h3><p>The first thing that caught me off guard is how different a microcontroller is from anything I had worked with before. A server has an operating system under it: a scheduler, a filesystem, a networking stack, a memory allocator. You write code on top of all that. A microcontroller has none of it. You get a chip, some flash memory, and a few hundred kilobytes of RAM. Whatever your program needs to do, it has to set up itself.</p><p>The most concrete expression of this is the <strong>GPIO</strong> pins (General Purpose Input/Output). These are the physical legs of the chip. Each pin is connected to a wire on the board, and your code can set it high (3.3V) or low (0V), or read its current state. A boolean, but made of electricity. Turning on an LED is literally setting a pin to `true`. Reading a button press is reading a pin’s value in a loop.</p><p>To make chips talk to each other, the embedded world uses a small set of standard protocols. The three I used in CyberKey are <strong>UART</strong>, <strong>I2C</strong>, and <strong>SPI</strong>. The analogy that clicked for me is that they fill roughly the same role as different network protocols in web development: each is a tradeoff between simplicity, speed, and the number of devices you can connect.</p><p>UART is the simplest: two wires, two devices, no shared clock. Both sides agree in advance on a speed (baud rate) and just send bits. It’s what’s behind the USB serial port you use to flash and debug a board. I2C uses only two wires but supports many devices on the same bus, each with an address, like an IP. It’s slower, but perfect for sensors and clocks that don’t need high throughput. SPI is the fastest: four wires, a dedicated clock, and it can push data at 80 MHz, which is why it’s used for displays.</p><p>What surprised me most was the hierarchy behind SPI. It has four wires: CLK (clock), MOSI (data out), MISO (data in), and CS (chip select). The first three form the <strong>bus</strong>, physically shared between all components like a single cable soldered to multiple chips at once. When the ESP32 sends a clock signal, every connected chip sees it simultaneously. The fourth wire, CS, is what makes one chip respond and not the others: when CS is pulled low for a specific chip, that chip listens; the rest ignore it.</p><p>In code, this maps to a clean hierarchy: a <strong>driver</strong> manages the three shared wires, and a <strong>device</strong> wraps that driver together with one specific CS pin to represent a single component. If you had a display and an SD card on the same bus, you’d have one driver and two devices, one per CS pin. The word “bus” is no accident. It’s the same metaphor as a city bus, a shared route that multiple passengers can board, each getting off at their own stop.</p><h3>The firmware architecture</h3><p>A web server entry point does a lot before it starts serving requests: it connects to the database, registers middleware, sets up routes, starts a background job queue. But underneath all of that, there’s an operating system managing memory and scheduling, a runtime handling I/O, a framework providing the event loop. You’re building on top of layers that already exist.</p><p>In embedded, those layers don’t exist. <em>main()</em> is not a starting point. It’s the entire program. In CyberKey’s firmware, <em>main()</em> is a long sequential initialization function:</p><p>- <strong>Power pin</strong>: a GPIO that must be held high immediately, or the board shuts off when you release the button<br>- <strong>Battery ADC: </strong>the analog-to-digital converter that reads the battery voltage; the chip only understands numbers, not voltages, so it needs hardware to translate<br>- <strong>UART for the CLI: </strong>the serial connection to a laptop, used to enroll fingerprints and sync the clock over USB<br>- <strong>I2C for the real-time clock: </strong>so the device knows what time it is to generate valid TOTP codes<br>- <strong>SPI for the display: </strong>the screen that shows the current status, the TOTP code, and the BLE pairing PIN<br>- <strong>BLE : </strong>Bluetooth Low Energy, the wireless protocol that makes the device appear as a keyboard to a computer<br>- <strong>Fingerprint sensor: </strong>connected via UART on the Grove port (a standardized connector from M5Stack that carries power and a communication protocol in a single plug, no soldering required)</p><p>Each component needs its own protocol configuration, its own pins, its own driver. Only once everything is initialized does control pass to the main loop.</p><p>The order matters. Initializing the display controller before completing its hardware reset sequence produces a black screen. Powering up BLE before the SPI bus is ready causes a crash. There’s no framework catching your mistakes. If the sequence is wrong, the device just doesn’t work, often without any error message.</p><p>After initialization, the firmware runs a loop that never exits. It checks the buttons, handles BLE events, listens for fingerprint matches, updates the display, reads the battery level. This is the event loop you write yourself.</p><p>One thing that has no equivalent in web development is power management. A device running on a 200 mAh battery drains fast, and every component you leave running costs you runtime. The ESP32 has sleep modes that should bring power down dramatically between uses. I spent a fair amount of time trying to make them work — and couldn’t. For reasons I never fully pinned down, the chip never actually slept. The simplest solution that did work: pressing button C cuts power entirely by driving a GPIO low. The board shuts off instantly, draws nothing, and reconnects to bonded hosts automatically in a few seconds on next boot.</p><h3>Rust in embedded: between C++ and nothing</h3><p>Rust is not the dominant language in embedded. C and C++ are. The official ESP32 SDK from Espressif (called ESP-IDF) is written in C. M5Stack’s official drivers are in C++. Most of the community, the tutorials, the examples: C and C++.</p><p>What makes Rust usable here is a layer of crates that wrap the ESP-IDF C code and expose it with a Rust API. When I call a function to read the battery voltage, it’s Rust on the front but C in the back. You get the safety guarantees of Rust, but you’re still standing on a foundation written in C.</p><p>The practical consequence is that reading C++ code became part of the workflow. To understand how a component behaves, the most reliable source is often the official C++ driver: which pin to toggle, in what order, with what timing. For the fingerprint sensor, M5Stack publishes an Arduino driver in C++. I read it, understood the UART communication protocol it implements, and rewrote it from scratch in Rust. Not because Rust required it, but because no Rust driver existed for that sensor.</p><p>This gave me a crate I called <em>fingerprint2-rs</em>, compiled with <em>no_std</em>. The <em>no_std</em> annotation tells the compiler this code cannot rely on the standard library, which assumes an operating system underneath. No OS, no standard library, no runtime overhead.</p><p>As for what Rust concretely brings: the compiler enforces error handling at every step, which matters when a failed I2C read can silently corrupt your state. Memory is managed explicitly, without a garbage collector. With a few hundred kilobytes to work with, that matters. I won’t oversell it: Rust didn’t make the hardware easier to understand. But it made the code easier to trust once it compiled.</p><h3>What web development doesn’t prepare you for</h3><p><strong>No hot reload.</strong> Every change on the firmware follows the same cycle: edit the code, compile, flash the binary onto the device over USB, wait for it to boot, observe. A full iteration takes around a minute. You learn quickly to think before you type.</p><p><strong>A crash can brick the device.</strong> In web development, an unhandled exception prints a stack trace and the process restarts. In embedded, bad firmware can leave the device in an infinite reboot loop with no output, or completely unresponsive. Bricking means the device becomes as useful as a brick: it won’t boot, and recovering it requires a specific flashing procedure if it’s even possible. It never happened to me on this project, but the possibility shapes how carefully you test each change.</p><p><strong>Memory is not elastic.</strong> The ESP32 has 520 KB of internal RAM. No heap growth, no swap, no “just add more”. Every allocation is a decision. This is where `no_std` earns its place: memory usage becomes explicit and predictable by design.</p><p><strong>The battery is always on your mind.</strong> In web development, energy consumption is invisible, it’s the cloud provider’s problem. On a device running on a 200 mAh battery, every component you leave running costs you autonomy. It forces a different way of thinking about every architectural decision, one I hadn’t anticipated at all coming from web.</p><h3>Developing with an AI as co-pilot</h3><p>I mentioned it in the intro, but it’s worth being specific: I relied heavily on Claude throughout this project. Not as a code generator I blindly trusted, but as a way to stay unblocked. When you have two hours before your baby wakes up, you can’t afford to spend forty-five minutes figuring out why your I2C bus is hanging. Having something that can explain the concept, point you to the relevant part, and sketch a direction changes the pace completely.</p><p>What it doesn’t replace is the decisions that require judgment. I drove the direction, the features, the architecture, the quality bar. When something didn’t work, I tested on the device, read the terminal output, and went looking for answers in M5Stack’s official documentation, their GitHub repositories, and a few open-source projects built on the same hardware. Several times that’s what finally unblocked us, not the AI. And sometimes it was just intuition that turned out to be right.</p><p>The risk I ran into: moving too fast. At several points I implemented something that worked, shipped it, and moved on without fully understanding what I had just written. It caught up with me later when something broke and I had to re-read my own code like it was someone else’s.</p><h3>Results and takeaways</h3><p>The device works. Place an enrolled finger, the sensor matches it, the TOTP code appears on the screen and is typed over Bluetooth in under a second. BLE pairing, the display, the real-time clock, the USB CLI: all of it functions as intended. For a first embedded project, I’m happy with where it landed.</p><p>The one disappointment is battery life. With a 200 mAh battery, the device lasts around 3–4 hours. I tried a lot of things to improve that — sleep modes, sensor standby, various combinations, and none of it moved the needle in any meaningful way. I never fully understood why. For now, the pragmatic solution is a hard power-off: one press of button C cuts all power at the hardware level, and the device reconnects to bonded hosts automatically on next boot. Not elegant, but honest. If you have an idea that doesn’t require hardware changes, I’d genuinely love to see a pull request.</p><p>If I did this again, I’d take more time upfront to understand the core concepts before writing any code. The moments where I got stuck hardest were always the moments where I had skipped the fundamentals. I’d also add logs from the very beginning, debugging embedded hardware without them means staring at a silent device and guessing.</p><p>The broader takeaway: embedded development is accessible to a web developer. The concepts are unfamiliar, but they’re learnable, and the instincts for clean architecture and readable code transfer well. It’s just a different kind of disorienting than picking up a new framework.</p><h3>One more thing: Cyberpunk 2077</h3><p>Part of what drives this project is Cyberpunk 2077. I played it two years ago, before my kid was born and, it was the original inspiration. CyberKey only borrows the aesthetic: the UI typeface, the color palette. But the broader idea is to build things that exist in that world and don’t exist yet in ours, with off-the-shelf hardware and a reasonable amount of work.</p><p>If there’s a piece of technology from the game you’d want to see built for real, I’d be curious to know. That’s where I’m going next.</p><p>Github: <a href="https://github.com/thomassimmer/CyberKey">https://github.com/thomassimmer/CyberKey</a><br>Demo: <a href="https://youtu.be/Q93ilcUGO0s">https://youtu.be/Q93ilcUGO0s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11cd89e5598" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Without Pylance: Using ty and Ruff on Cursor or Antigravity]]></title>
            <link>https://medium.com/@thomas.simmer/python-without-pylance-using-ty-and-ruff-on-cursor-or-antigravity-05a50a9299f8?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/05a50a9299f8</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[antigravity]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 21:09:39 GMT</pubDate>
            <atom:updated>2026-01-19T21:09:39.233Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re using Cursor or Antigravity for Python, you may have noticed a recurring issue:<br><strong>Pylance isn’t available.</strong></p><p>On forums, this often comes up as a blocker, especially for developers used to strong type checking and fast editor feedback. What’s less known is that Pylance is no longer the only serious option in this space.</p><h3>ty: A Viable Alternative for Type Checking</h3><p><a href="https://github.com/astral-sh/ty">ty</a> is a Python type checker developed by Astral, the team behind <a href="https://astral.sh/ruff">Ruff</a>.<br>It’s written in Rust and designed with performance in mind.</p><p>In practice, it offers:</p><ul><li>fast type analysis, even on larger codebases,</li><li>clean integration via LSP with editors like Cursor or Antigravity,</li><li>no dependency on VS Code or proprietary extensions.</li></ul><p>ty is still relatively young and doesn’t try to fully replicate Pylance feature-for-feature. However, for many projects, it already provides useful and responsive type feedback.</p><h3>Ruff: Fast Linting and Formatting</h3><p><a href="https://astral.sh/ruff">Ruff</a> is more established and often easier to adopt. It combines linting and formatting in a single tool and can replace a large part of the traditional Python tooling stack.</p><p>Its main advantage is speed. Being written in Rust, it runs fast enough to stay enabled at all times, which helps maintain short feedback loops even in larger repositories.</p><h3>Open Source and Permissive by Design</h3><p>One important aspect of Astral’s tooling is that all of these tools are fully open source, released under permissive licenses.</p><p>This means:</p><ul><li>anyone can inspect how they work,</li><li>anyone can contribute improvements or fixes,</li><li>and there’s no lock-in to a specific editor or vendor.</li></ul><p>For developers who care about transparency, long-term maintainability, or simply being able to participate in the ecosystem, this is a meaningful difference compared to more closed alternatives.</p><h3>A Consistent Tooling Stack</h3><p>Alongside Ruff and ty, Astral also maintains <a href="https://github.com/astral-sh/uv">uv</a>, a fast dependency and environment manager.<br>While each tool can be used independently, they share the same general philosophy:</p><ul><li>performance-first,</li><li>minimal configuration,</li><li>editor-agnostic tooling.</li></ul><p>You don’t need to adopt the full stack, but even partially, it helps reduce friction when working on Python projects outside VS Code.</p><h3>For Cursor and Antigravity Users</h3><p>If you avoided Cursor or Antigravity because “Python without Pylance isn’t comfortable enough”, that assumption is increasingly outdated.</p><p>With:</p><ul><li>ty for type checking,</li><li>Ruff for linting and formatting,</li></ul><p>you can get a setup that is responsive, modern, and works well in these editors.</p><p>This isn’t about replacing Pylance everywhere. It’s about knowing that solid, open alternatives now exist — and that they’re good enough to unblock real-world workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05a50a9299f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#[sqlx::test]: A Powerful Example of Macros and Traits in Rust]]></title>
            <link>https://medium.com/@thomas.simmer/sqlx-test-a-powerful-example-of-macros-and-traits-in-rust-1d0a5b3bd1b1?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d0a5b3bd1b1</guid>
            <category><![CDATA[sqlx]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-macros]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 21:30:28 GMT</pubDate>
            <atom:updated>2025-11-13T21:30:28.265Z</atom:updated>
            <content:encoded><![CDATA[<p>When writing integration tests for the Rust web APIs of <a href="https://github.com/thomassimmer/Flutter-Actix-App">the Flutter-Actix app</a> and <a href="https://github.com/thomassimmer/reallystick">ReallyStick</a>, I discovered that SQLx’s <strong>#[sqlx::test]</strong> macro not only simplified my code but also solved a disk space problem. More importantly, I learned a valuable lesson: <strong>always read the crate documentation instead of blindly following tutorials</strong>. But beyond that, <strong>#[sqlx::test]</strong> is a perfect example of how Rust’s macro system and trait system work together to create powerful abstractions.</p><p>I had been following the <a href="https://www.lpalmieri.com/posts/2020-08-31-zero-to-production-3-5-html-forms-databases-integration-tests/#3-2-choosing-a-database-crate">zero2prod</a> book’s approach of manually creating databases for each test. While this worked, it led to hundreds of orphaned databases consuming gigabytes of disk space. SQLx’s <strong>#[sqlx::test]</strong> macro solves this elegantly. Let’s dive into how it works under the hood.</p><h4>The Problem (Briefly)</h4><p>The original approach manually created a database for each test:</p><pre>#[tokio::test]<br>async fn user_can_login() {<br>    let app = spawn_app().await;  // Creates DB using a UUID, runs migrations<br>    // test code<br>}</pre><p>This worked but had two critical issues: <strong>no automatic cleanup</strong> (databases accumulated indefinitely) and <strong>verbose boilerplate</strong> (30+ lines of setup code). After running my tests multiple times, I had hundreds of orphaned databases.</p><h4>The Solution: #[sqlx::test]</h4><p>The fix was simple: just change the attribute and add a parameter:</p><pre>#[sqlx::test]<br>async fn user_can_login(pool: PgPool) {<br>    let app = spawn_app(pool).await;<br>    // test code<br>}</pre><p>But what makes this work? Let’s examine SQLx’s implementation to understand the magic.</p><h4>How #[sqlx::test] Works: A Deep Dive</h4><p><strong>Step 1: Macro Expansion</strong></p><p>When you write <strong>#[sqlx::test]</strong>, the procedural macro in <strong>sqlx-macros-core/src/test_attr.rs</strong> transforms your function. Here’s the key expansion logic:</p><p>File: sqlx-macros-core-0.7.4/src/test_attr.rs</p><pre>Ok(quote! {<br>    #[::core::prelude::v1::test]<br>    #(#attrs)*<br>    fn #name() #ret {<br>        async fn #name(#inputs) #ret {<br>            #body<br>        }<br><br>        let mut args = ::sqlx::testing::TestArgs::new(<br>            concat!(module_path!(), &quot;::&quot;, stringify!(#name))<br>        );<br><br>        #migrations  // Adds migrator if migrations/ directory exists<br><br>        args.fixtures(&amp;[#(#fixtures),*]);<br><br>        let f: fn(#(#fn_arg_types),*) -&gt; _ = #name;<br>        ::sqlx::testing::TestFn::run_test(f, args)<br>    }<br>})</pre><p>The macro:</p><p>1. Wraps your async function in a regular `#[test]` function</p><p>2. Creates a `TestArgs` struct with your test’s full path (for tracking)</p><p>3. Automatically detects and includes migrations from `./migrations/`</p><p>4. Creates a function pointer to your async function</p><p>5. Calls `TestFn::run_test()` which handles the entire lifecycle</p><p>The key line is `let f: fn(#(#fn_arg_types),*) -&gt; _ = #name;`. This extracts your function signature (including the `pool: PgPool` parameter) and creates a function pointer. For your test, this becomes `let f: fn(PgPool) -&gt; _ = user_can_login;`.</p><p><strong>Step 1.1: How the PgPool Parameter Works</strong></p><p>You might wonder: how does SQLx know to create a `PgPool` and pass it to your function? This is where Rust’s trait system shines.</p><p>When the macro calls `TestFn::run_test(f, args)`, it relies on trait implementations that match your function signature. SQLx provides a `TestFn` trait with implementations for specific function signatures:</p><p>File: sqlx-core-0.7.4/src/testing/mod.rs</p><pre>impl&lt;DB, Fut&gt; TestFn for fn(Pool&lt;DB&gt;) -&gt; Fut<br>where<br>    DB: TestSupport + Database,<br>    DB::Connection: Migrate,<br>    for&lt;&#39;c&gt; &amp;&#39;c mut DB::Connection: Executor&lt;&#39;c, Database = DB&gt;,<br>    Fut: Future,<br>    Fut::Output: TestTermination,<br>{<br>    type Output = Fut::Output;<br><br>    fn run_test(self, args: TestArgs) -&gt; Self::Output {<br>        run_test_with_pool(args, self)  // self is your function!<br>    }<br>}</pre><p>When you write `async fn user_can_login(pool: PgPool)`, the function pointer type is `fn(PgPool) -&gt; impl Future`. Rust’s trait resolution matches this to the `TestFn` implementation above (since `PgPool` is `Pool&lt;Postgres&gt;`).</p><p>The implementation then calls `run_test_with_pool`, which creates the pool and calls your function:</p><p>File: sqlx-core-0.7.4/src/testing/mod.rs</p><pre>fn run_test_with_pool&lt;DB, F, Fut&gt;(args: TestArgs, test_fn: F) -&gt; Fut::Output<br>where<br>    F: FnOnce(Pool&lt;DB&gt;) -&gt; Fut,  // Your function matches this!<br>    // ...<br>{<br>    run_test::&lt;DB, _, _&gt;(args, |pool_opts, connect_opts| async move {<br>        // Create the actual pool<br>        let pool = pool_opts<br>            .connect_with(connect_opts)<br>            .await<br>            .expect(&quot;failed to connect test pool&quot;);<br><br>        // Call your function with the pool!<br>        let res = test_fn(pool.clone()).await;<br>        //     ^^^^^^^^^^^^<br>        //     This is your function being called<br><br>        // ... cleanup code ...<br>        res<br>    })<br>}</pre><p>The critical line is `test_fn(pool.clone()).await`. This invokes your function, passing the freshly created pool as the argument.</p><p><strong>The Magic</strong>: Rust’s trait system connects your function signature to the pool creation logic. The macro extracts your function signature, the trait system matches it to the right implementation, and that implementation creates the pool and calls your function. This is why you can write `async fn my_test(pool: PgPool)`. The plumbing is handled automatically.</p><p><strong>Step 2: Test Execution Flow</strong></p><p>The `run_test` function orchestrates the test lifecycle:</p><p>File: sqlx-core-0.7.4/src/testing/mod.rs</p><pre>fn run_test&lt;DB, F, Fut&gt;(args: TestArgs, test_fn: F) -&gt; Fut::Output<br>where<br>    DB: TestSupport,<br>    DB::Connection: Migrate,<br>    // ... trait bounds<br>{<br>    crate::rt::test_block_on(async move {<br>        // 1. Create test database context<br>        let test_context = DB::test_context(&amp;args)<br>            .await<br>            .expect(&quot;failed to connect to setup test database&quot;);<br><br>        // 2. Setup database (migrations + fixtures)<br>        setup_test_db::&lt;DB&gt;(&amp;test_context.connect_opts, &amp;args).await;<br><br>        // 3. Execute your test function<br>        let res = test_fn(test_context.pool_opts, test_context.connect_opts).await;<br><br>        // 4. Cleanup: delete database if test succeeded<br>        if res.is_success() {<br>            if let Err(e) = DB::cleanup_test(&amp;test_context.db_name).await {<br>                eprintln!(&quot;failed to delete database {:?}: {}&quot;, test_context.db_name, e);<br>            }<br>        }<br><br>        res<br>    })<br>}</pre><p>This is the heart of the system. Notice that cleanup only happens if `res.is_success()`. Failed tests keep their databases for debugging.</p><p><strong>Step 3: Database Creation</strong></p><p>The PostgreSQL-specific implementation creates unique databases using a sequence:</p><p>File: sqlx-postgres-0.7.4/src/testing/mod.rs</p><pre>async fn test_context(args: &amp;TestArgs) -&gt; Result&lt;TestContext&lt;Postgres&gt;, Error&gt; {<br>    let url = dotenvy::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set&quot;);<br>    let master_opts = PgConnectOptions::from_str(&amp;url)<br>        .expect(&quot;failed to parse DATABASE_URL&quot;);<br><br>    // Create a &quot;master&quot; pool for database management<br>    let master_pool = PoolOptions::new()<br>        .max_connections(20)<br>        .after_release(|_conn, _| Box::pin(async move { Ok(false) }))<br>        .connect_lazy_with(master_opts);<br><br>    let mut conn = master_pool.acquire().await?;<br><br>    // Create tracking schema and table<br>    conn.execute(r#&quot;<br>        lock table pg_catalog.pg_namespace in share row exclusive mode;<br>        create schema if not exists _sqlx_test;<br>        create table if not exists _sqlx_test.databases (<br>            db_name text primary key,<br>            test_path text not null,<br>            created_at timestamptz not null default now()<br>        );<br>        create sequence if not exists _sqlx_test.database_ids;<br>    &quot;#).await?;<br><br>    // Cleanup old databases (only on first test run)<br>    let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();<br>    if DO_CLEANUP.swap(false, Ordering::SeqCst) {<br>        do_cleanup(&amp;mut conn, now).await?;<br>    }<br><br>    // Generate unique database name using PostgreSQL sequence<br>    let new_db_name: String = query_scalar(r#&quot;<br>        insert into _sqlx_test.databases(db_name, test_path)<br>        select &#39;_sqlx_test_&#39; || nextval(&#39;_sqlx_test.database_ids&#39;), $1<br>        returning db_name<br>    &quot;#)<br>    .bind(&amp;args.test_path)<br>    .fetch_one(&amp;mut *conn)<br>    .await?;<br><br>    // CREATE THE ACTUAL DATABASE<br>    conn.execute(&amp;format!(&quot;create database {new_db_name:?}&quot;)[..])<br>        .await?;<br><br>    Ok(TestContext {<br>        pool_opts: PoolOptions::new()<br>            .max_connections(5)<br>            .idle_timeout(Some(Duration::from_secs(1)))<br>            .parent(master_pool.clone()),<br>        connect_opts: master_opts.clone().database(&amp;new_db_name),<br>        db_name: new_db_name,<br>    })<br>}</pre><p>Key design decisions:</p><p>- <strong>Sequence-based naming</strong>: Uses PostgreSQL’s `nextval()` to generate unique names (`_sqlx_test_1`, `_sqlx_test_2`, etc.)</p><p>- <strong>Tracking table</strong>: Records all test databases with their test paths and creation times</p><p>- <strong>Automatic cleanup</strong>: On the first test run, deletes databases older than the current time</p><p>- <strong>Parent pool</strong>: Test pools share a “parent” pool to manage connection limits globally</p><p><strong>Step 4: Migration Application</strong></p><p>After creating the database, migrations are applied automatically:</p><p>File: sqlx-core-0.7.4/src/testing/mod.rs</p><pre>async fn setup_test_db&lt;DB: Database&gt;(<br>    copts: &amp;&lt;DB::Connection as Connection&gt;::Options,<br>    args: &amp;TestArgs,<br>) where<br>    DB::Connection: Migrate + Sized,<br>    // ... trait bounds<br>{<br>    let mut conn = copts<br>        .connect()<br>        .await<br>        .expect(&quot;failed to connect to test database&quot;);<br><br>    // Apply migrations if migrator was provided<br>    if let Some(migrator) = args.migrator {<br>        migrator<br>            .run_direct(&amp;mut conn)<br>            .await<br>            .expect(&quot;failed to apply migrations&quot;);<br>    }<br><br>    // Apply test fixtures (SQL scripts)<br>    for fixture in args.fixtures {<br>        (&amp;mut conn)<br>            .execute(fixture.contents)<br>            .await<br>            .unwrap_or_else(|e| panic!(&quot;failed to apply test fixture {:?}: {:?}&quot;, fixture.path, e));<br>    }<br><br>    conn.close().await.expect(&quot;failed to close setup connection&quot;);<br>}</pre><p>The macro automatically detects your `./migrations/` directory and includes it in `TestArgs`. The `migrator.run_direct()` method applies all migrations in order.</p><p><strong>Step 5: Automatic Cleanup</strong></p><p>The cleanup happens automatically after successful tests:</p><p>File: sqlx-postgres-0.7.4/src/testing/mod.rs</p><pre>fn cleanup_test(db_name: &amp;str) -&gt; BoxFuture&lt;&#39;_, Result&lt;(), Error&gt;&gt; {<br>    Box::pin(async move {<br>        let mut conn = MASTER_POOL<br>            .get()<br>            .expect(&quot;cleanup_test() invoked outside `#[sqlx::test]&quot;)<br>            .acquire()<br>            .await?;<br><br>        // Drop the database<br>        conn.execute(&amp;format!(&quot;drop database if exists {db_name:?};&quot;)[..])<br>            .await?;<br><br>        // Remove from tracking table<br>        query(&quot;delete from _sqlx_test.databases where db_name = $1&quot;)<br>            .bind(&amp;db_name)<br>            .execute(&amp;mut *conn)<br>            .await?;<br><br>        Ok(())<br>    })<br>}</pre><p>This is the critical piece that solves the disk space problem. Each database is automatically deleted after its test completes, preventing accumulation.</p><p><strong>The Architecture: Why It Works So Well</strong></p><p>SQLx’s design is elegant:</p><p>1. <strong>Database-per-test isolation</strong>: Each test gets a completely fresh database, enabling safe parallel execution</p><p>2. <strong>Automatic migration management</strong>: No need to manually run migrations</p><p>3. <strong>Resource tracking</strong>: The `_sqlx_test.databases` table tracks all test databases, enabling cleanup of orphaned ones</p><p>4. <strong>Failure handling</strong>: Failed tests keep their databases for debugging, successful ones are cleaned up immediately</p><p>5. <strong>Connection pooling</strong>: Smart pool management prevents connection exhaustion across parallel tests</p><p><strong>The Lesson: Read the Documentation</strong></p><p>Here’s what I learned: <strong>Don’t follow tutorials blindly</strong>. The <a href="https://www.lpalmieri.com/posts/2020-08-31-zero-to-production-3-5-html-forms-databases-integration-tests/#3-2-choosing-a-database-crate">zero2prod</a> book showed a valid approach, but it wasn’t the best one for my use case. SQLx’s documentation clearly describes <strong>#[sqlx::test]</strong> and its benefits, but I hadn’t checked it.</p><p>A few minutes reading the SQLx docs would have saved me some lines of boilerplate code, gigabytes of disk space, and manual cleanup scripts.</p><p><strong>Always check the crate’s documentation for built-in solutions before implementing your own</strong>. Library authors often provide utilities specifically designed for common use cases like testing. The <strong>#[sqlx::test] </strong>macro is a perfect example of how Rust’s macro system can make testing both simpler and more robust.</p><p><em>Sometimes the best code is the code you don’t have to write — and sometimes it’s already written in the crate’s documentation.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Esvb-5YxIHBogaoe9xftA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d0a5b3bd1b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReallyStick: An Open-Source Habit Tracker Built with Flutter & Rust]]></title>
            <link>https://medium.com/@thomas.simmer/reallystick-an-open-source-habit-tracker-built-with-flutter-rust-6b4f748512d1?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b4f748512d1</guid>
            <category><![CDATA[habit-building]]></category>
            <category><![CDATA[apps]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 18:07:29 GMT</pubDate>
            <atom:updated>2025-10-14T18:07:29.411Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A year ago, my wife and I started building <strong>ReallyStick</strong>, an open-source app to track habits, create custom challenges, and connect with a community. Built on a <a href="https://github.com/thomassimmer/Flutter-Actix-App"><strong>Flutter/Actix template</strong></a> I’d already open-sourced (and wrote <a href="https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-a-beginners-journey-92cbb893c2f9">four Medium articles</a> about), it was designed to make personal growth collaborative and motivating.</p><p>Today, we’re releasing it as-is — <strong>unfinished, but functional</strong>. Why? Because it might inspire other developers, serve as a foundation for new projects, or simply showcase what’s possible with Flutter and Rust. And because life happened: our baby arrived, reshuffling our priorities.</p><h3>1. What Is ReallyStick?</h3><p>ReallyStick lets users:</p><ul><li><strong>Track habits</strong> (e.g., exercise, meditation, learning) and watch <strong>global analytics</strong> for each of them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-D6pX4rF_RqZkuy9IyqHQ.png" /></figure><ul><li><strong>Create or join challenges</strong> (e.g., <em>“30 Days No Sugar”</em>, <em>“10K Steps/Day”</em>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p14IBlObUbtWdH4G7H7Dog.png" /></figure><ul><li><strong>Engage with a community</strong> via public threads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asVqEnpca_E1rOkh2gbwKw.png" /></figure><ul><li><strong>Chat with people </strong>via end-to-end encrypted private messages.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PFf-8tXZfi6aTGbhFJwkA.png" /></figure><p><em>Technically, it uses:</em></p><ul><li><strong>Flutter</strong> for the frontend (web + mobile).</li><li><strong>Rust (Actix)</strong> for the backend API.</li><li><strong>PostgreSQL</strong> for data storage.</li><li><strong>Client-side encryption</strong> for private messages.</li></ul><p>It is accessible on the web right now <a href="https://reallystick.com/">here</a>. Give it a try, it is entirely free!</p><h3>2. Why I Stopped Developing It</h3><p>So why pause such an ambitious project? A few reasons:</p><ul><li><strong>Our baby arrived</strong>: Sleepless nights and new responsibilities left little time for coding.</li><li><strong>A crowded market</strong>: Apps like Notion, Habitica and Disciplined already dominate the space. ReallyStick needed a stronger USP.</li><li><strong>Lack of user feedback</strong>: Without a testing community, it was hard to prioritize features.</li></ul><p><em>But ultimately, we realized our core goal — </em><strong><em>building something useful</em></strong><em> — was already met. Even unfinished, ReallyStick works, and its code can help others.</em></p><h3>3. Why Release It Anyway?</h3><p>Here’s why we are now open-sourcing it:</p><ol><li><strong>To inspire</strong>: Maybe another dev will fork it, improve it, or use it as a learning tool.</li><li><strong>For job hunting</strong>: It’s a concrete example of our skills.</li><li><strong>Transparency</strong>: Incomplete projects have value too. Development is iterative, with ups and downs.</li></ol><p><em>If you want to contribute, the repo is here: </em><a href="https://github.com/thomassimmer/reallystick"><em>GitHub Link</em></a><em>. Issues are open, and we’d love to chat!</em></p><h3>4. Key Takeaways</h3><p>This project taught me:</p><ul><li><strong>User testing matters</strong>: Without feedback, it’s hard to know if you’re on the right track.</li><li><strong>Rust’s power</strong>: After using Node.js/Python, Rust won me over with its performance and safety.</li><li><strong>Priorities shift</strong>: Sometimes, you have to pause a project to focus on what truly matters (like family!).</li></ul><h3>Conclusion</h3><p>ReallyStick is an open-source project we won’t actively develop further — but it’s functional and ready for exploration. If you’re a developer looking for a project to contribute to, or just curious about Flutter/Rust integration, dive into the code!</p><p><strong>Want a deep dive?</strong> If you’re interested in a specific part of the project (e.g., the encryption system, Flutter/Rust integration, or deployment), <strong>let me know in the comments</strong> — I’d be happy to write a follow-up article!</p><p><em>And if you liked this post, share it! Check out my </em><a href="https://github.com/thomassimmer/Flutter-Actix-App"><em>Flutter/Actix template</em></a><em> if you’re starting a similar project. 🚀</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Ut6S4AR_8Ktd6YVUN_MGBA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b4f748512d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Cross-Platform App with Flutter and Rust: JWT & Session Deactivation]]></title>
            <link>https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-jwt-session-deactivation-8ffad3d7ab5a?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ffad3d7ab5a</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[actix-web]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 15:31:46 GMT</pubDate>
            <atom:updated>2025-11-14T13:39:20.615Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Welcome to the next article in my series on building a cross-platform app using Flutter for the frontend and Rust (via Actix) for the backend. In this article, I’ll share how I implemented efficient JWT (JSON Web Token) validation and session deactivation mechanisms, tackling an important optimization that significantly improved the backend performance and enhanced the user experience.</p><p>For more context, you can start by reading <a href="https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-a-beginners-journey-92cbb893c2f9">the first article</a> in this series, where I outlined the initial setup and my approach to combining these two powerful technologies.</p><p>A few weeks after releasing the initial version of this project, I began building a new application based on this template. It quickly became apparent that my authentication logic needed optimization. The middleware I originally wrote to validate JWTs decrypted the token and queried the database to match the user by performing a join operation on the users and user_tokens tables for every authenticated request. As you can imagine, this introduced significant overhead by hitting the database far too often — clearly, not ideal.</p><p>You might be wondering: Why was I saving JWT IDs in the database in the first place? After all, JWTs are designed to carry all the necessary information in a secure, self-contained format, and you typically don’t need to store them. However, I used a user_tokens table to enable session deactivation on specific devices. The catch? I hadn’t actually implemented the session deactivation feature, rendering the entire setup inefficient without serving its intended purpose.</p><p>This article is about fixing that oversight and implementing a robust mechanism for session deactivation while ensuring efficient JWT validation.</p><h3><strong>Optimizing JWT Validation</strong></h3><p>To address the inefficiencies in my initial approach, the new JWT validation mechanism now works as follows:</p><p>1. Extract Useful Properties from the JWT</p><p>The middleware decodes the JWT to directly extract commonly used properties, such as user.id and user.is_admin. These are frequently required by routes, so extracting them upfront avoids redundant database queries.</p><p>2. Check for Revoked Tokens</p><p>To ensure security, the middleware verifies that the JWT has not been revoked by querying the user_tokens table. This ensures sessions can still be deactivated when necessary.</p><p>3. Implement Token Caching</p><p>To reduce database load, verified tokens are cached. This means the database is queried only if the JWT is not already in the cache.</p><p>4. Pass JWT Claims Through Requests</p><p>Decoded claims from the JWT are passed along with the request context, making them easily accessible to downstream handlers.</p><h4>Benefits of the New Approach:</h4><p>• Reduced Database Queries: Instead of performing a database join for every authenticated request, the database is queried only when a JWT is missing from the cache and, the query is a simple ‘SELECT’.</p><p>• Streamlined User Data Access: Routes that need full user data now perform a simple SELECT query on the users table using the user_id provided in the JWT claims, rather than relying on an expensive join operation.</p><p>• Enhanced Security &amp; User Insights: The caching mechanism tracks the last activity for each token, allowing for better session monitoring and management.</p><p>Below is how I implemented the middleware:</p><pre>pub struct TokenValidator {}<br><br>impl&lt;S, B&gt; Transform&lt;S, ServiceRequest&gt; for TokenValidator<br>where<br>    S: Service&lt;ServiceRequest, Response = ServiceResponse&lt;B&gt;, Error = Error&gt; + &#39;static,<br>    S::Future: &#39;static,<br>    B: &#39;static,<br>{<br>    type Response = ServiceResponse&lt;EitherBody&lt;B&gt;&gt;;<br>    type Error = Error;<br>    type Transform = TokenValidatorMiddleware&lt;S&gt;;<br>    type InitError = ();<br>    type Future = Ready&lt;Result&lt;Self::Transform, Self::InitError&gt;&gt;;<br><br>    fn new_transform(&amp;self, service: S) -&gt; Self::Future {<br>        ready(Ok(TokenValidatorMiddleware {<br>            service: Rc::new(service),<br>        }))<br>    }<br>}<br><br>pub struct TokenValidatorMiddleware&lt;S&gt; {<br>    service: Rc&lt;S&gt;,<br>}<br><br>impl&lt;S, B&gt; Service&lt;ServiceRequest&gt; for TokenValidatorMiddleware&lt;S&gt;<br>where<br>    S: Service&lt;ServiceRequest, Response = ServiceResponse&lt;B&gt;, Error = Error&gt; + &#39;static,<br>    S::Future: &#39;static,<br>    B: &#39;static,<br>{<br>    type Response = ServiceResponse&lt;EitherBody&lt;B&gt;&gt;;<br>    type Error = Error;<br>    type Future = LocalBoxFuture&lt;&#39;static, Result&lt;Self::Response, Self::Error&gt;&gt;;<br><br>    forward_ready!(service);<br><br>    fn call(&amp;self, req: ServiceRequest) -&gt; Self::Future {<br>        let service = Rc::clone(&amp;self.service);<br><br>        let secret = req.app_data::&lt;Data&lt;String&gt;&gt;().unwrap().to_string();<br>        let pool = req.app_data::&lt;Data&lt;PgPool&gt;&gt;().unwrap().clone();<br>        let cached_tokens = req.app_data::&lt;Data&lt;TokenCache&gt;&gt;().unwrap().clone();<br><br>        Box::pin(async move {<br>            match retrieve_claims_for_token(req.request().clone(), secret) {<br>                Ok(claims) =&gt; {<br>                    if now() &gt; DateTime::&lt;Utc&gt;::from_timestamp(claims.exp, 0).unwrap() {<br>                        return Ok(req.into_response(<br>                            HttpResponse::Unauthorized()<br>                                .json(AppError::AccessTokenExpired.to_response())<br>                                .map_into_right_body(),<br>                        ));<br>                    }<br><br>                    let last_activity_for_this_token =<br>                        cached_tokens.get_value_for_key(claims.jti).await;<br><br>                    match last_activity_for_this_token {<br>                        Some(last_activity) =&gt; {<br>                            // Update only if last activity is more than 5 minutes ago<br>                            // To not update too often<br>                            if now() - Duration::minutes(5) &gt; last_activity {<br>                                cached_tokens.update_or_insert_key(claims.jti, now()).await;<br>                            }<br>                        }<br>                        None =&gt; {<br>                            // Check if token still exists (it could have been revoked)<br>                            let existing_token =<br>                                get_user_token(&amp;**pool, claims.user_id, claims.jti).await;<br><br>                            match existing_token {<br>                                Ok(r) =&gt; {<br>                                    if r.is_none() {<br>                                        return Ok(req.into_response(<br>                                            HttpResponse::Unauthorized()<br>                                                .json(AppError::InvalidAccessToken.to_response())<br>                                                .map_into_right_body(),<br>                                        ));<br>                                    }<br>                                }<br>                                Err(e) =&gt; {<br>                                    error!(&quot;Error: {}&quot;, e);<br>                                    return Ok(req.into_response(<br>                                        HttpResponse::InternalServerError()<br>                                            .json(AppError::DatabaseQuery.to_response())<br>                                            .map_into_right_body(),<br>                                    ));<br>                                }<br>                            };<br><br>                            cached_tokens.update_or_insert_key(claims.jti, now()).await;<br>                        }<br>                    }<br><br>                    // Store claims in request extensions for ReqData extractor<br>                    req.extensions_mut().insert(claims);<br>                    let res = service.call(req).await?;<br>                    Ok(res.map_into_left_body())<br>                }<br>                Err(_) =&gt; Ok(req.into_response(<br>                    HttpResponse::Unauthorized()<br>                        .json(AppError::InvalidAccessToken.to_response())<br>                        .map_into_right_body(),<br>                )),<br>            }<br>        })<br>    }<br>}</pre><p>You can notice a cached_tokens state variable. It is a simple HashMap where:</p><p>• Key: The JWT ID.</p><p>• Value: The DateTime of the token’s last activity, allowing you to track user sessions on specific devices.</p><p>Here’s the implementation of the cached_tokens:</p><pre>#[derive(Default, Clone)]<br>pub struct TokenCache {<br>    data: Arc&lt;RwLock&lt;HashMap&lt;Uuid, DateTime&lt;Utc&gt;&gt;&gt;&gt;,<br>}<br><br>impl TokenCache {<br>    pub async fn update_or_insert_key(&amp;self, key: Uuid, value: DateTime&lt;Utc&gt;) {<br>        self.data<br>            .write()<br>            .await<br>            .entry(key)<br>            .and_modify(|v| *v = value)<br>            .or_insert(value);<br>    }<br><br>    pub async fn remove_key(&amp;self, key: Uuid) {<br>        self.data.write().await.remove(&amp;key);<br>    }<br><br>    pub async fn get_value_for_key(&amp;self, key: Uuid) -&gt; Option&lt;DateTime&lt;Utc&gt;&gt; {<br>        self.data.read().await.get(&amp;key).cloned()<br>    }<br>}</pre><p>This setup ensures efficient token validation while maintaining flexibility to manage session state securely.</p><h3><strong>Session Deactivation</strong></h3><p>Session deactivation is an essential feature for any secure app, especially in scenarios like losing your phone or having it stolen. To enable users to log out of specific sessions, we first need a reliable way to identify each device connected to the server.</p><h4><strong>Storing Device Information</strong></h4><p>Since each device corresponds to a unique JWT, we can store device-specific information in the user_tokens table alongside the JWT ID. This enables us to provide detailed session information to users. However, building a multi-platform app introduces a challenge: identifying the device making the request. Unlike web-only apps where you can parse a standard User-Agent header, mobile and desktop apps require a custom approach.</p><h4><strong>Using device_info_plus for Device Identification</strong></h4><p>Fortunately, the <a href="https://pub.dev/packages/device_info_plus">device_info_plus</a> package in Flutter provides detailed information about the platform, OS version, model, and more. Using this package, I built a custom user agent string that contains essential details about the device in a structured format. Here’s the function that generates the custom user agent:</p><pre>import &#39;dart:io&#39;;<br><br>import &#39;package:device_info_plus/device_info_plus.dart&#39;;<br>import &#39;package:flutter/foundation.dart&#39; show kIsWeb;<br>import &#39;package:universal_io/io.dart&#39;;<br><br>const String appVersion = &#39;1.0.0&#39;;<br>String? _cachedUserAgent; // Private variable to store the cached result.<br><br>Future&lt;String&gt; getUserAgent() async {<br>  // Return the cached value if it exists.<br>  if (_cachedUserAgent != null) {<br>    return _cachedUserAgent!;<br>  }<br><br>  final deviceInfo = DeviceInfoPlugin();<br>  Map&lt;String, dynamic&gt; userAgentData = {<br>    &#39;appVersion&#39;: appVersion,<br>    &#39;os&#39;: Platform.operatingSystem,<br>    &#39;isMobile&#39;: Platform.isAndroid || Platform.isIOS,<br>  };<br><br>  if (kIsWeb) {<br>    // Web-specific info<br>    final webInfo = await deviceInfo.webBrowserInfo;<br>    userAgentData[&#39;browser&#39;] = webInfo.browserName.name;<br>  } else if (Platform.isAndroid) {<br>    // Android-specific info<br>    final androidInfo = await deviceInfo.androidInfo;<br>    userAgentData[&#39;model&#39;] = androidInfo.model;<br>  } else if (Platform.isIOS) {<br>    // iOS-specific info<br>    final iosInfo = await deviceInfo.iosInfo;<br>    userAgentData[&#39;model&#39;] = iosInfo.name;<br>  } else if (Platform.isMacOS) {<br>    // macOS-specific info<br>    final macosInfo = await deviceInfo.macOsInfo;<br>    userAgentData[&#39;model&#39;] = macosInfo.model;<br>  }<br><br>  // Serialize the map to a JSON-like string for the User-Agent<br>  _cachedUserAgent = userAgentData.entries<br>      .map((entry) =&gt; &#39;${entry.key}=${entry.value}&#39;)<br>      .join(&#39;; &#39;);<br><br>  return _cachedUserAgent!;<br>}</pre><p>The result is a concise and easily parsable string that describes the device making the request.</p><h4><strong>Sending the Custom User Agent</strong></h4><p>Since modifying the standard User-Agent header is restricted, I send the custom user agent in a new header: X-User-Agent. To process this header, you need to explicitly allow it in Actix’s CORS configuration. Here’s a snippet to enable it:</p><pre>use actix_cors::Cors;<br><br>let cors = Cors::default()<br>.allowed_headers(vec![<br>        http::header::AUTHORIZATION,<br>        http::header::CONTENT_TYPE,<br>        http::header::HeaderName::from_static(&quot;x-user-agent&quot;),<br>    ])<br>.allow_any_origin()<br>.max_age(3600);</pre><h4><strong>Saving Device Information</strong></h4><p>Whenever a user logs in, the backend parses the X-User-Agent header and saves the extracted device information in the user_tokens table along with the JWT ID. This makes it possible to display active sessions to the user, complete with details about each device.</p><h4><strong>Session Management Endpoints</strong></h4><p>With device information stored in the user_tokens table, we need two endpoints to manage sessions:</p><p>1. Get Active Sessions: Returns a list of the user’s active sessions, including device details and the last activity timestamp.</p><p>2. Revoke a Session: Deletes a specific session (based on the token ID) from the user_tokens table.</p><p>I won’t go into the implementation details here, as it closely mirrors what I described in the previous article on locale selection. The key concepts and database interactions remain largely the same.</p><h4><strong>User Experience</strong></h4><p>With these endpoints in place, users can view all active sessions in their account settings and revoke any session.</p><p>Below are screenshots of how the feature appears in the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DsQwYPjlhu-1BoAI9zJy8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYOVtergn0UY99PRhcx7nw.png" /></figure><p>If you’re interested in the implementation details, you can check out the code <a href="https://github.com/thomassimmer/Flutter-Actix-App">here</a>.</p><p>Feel free to leave a comment if you have any questions or suggestions for improvement.</p><p>Thanks for reading, and see you in the next article, where I’ll probably share my new application!</p><p>Thomas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a_MlBYge76XH4RXf.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ffad3d7ab5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust: Build a Simple Celery-like Worker]]></title>
            <link>https://medium.com/@thomas.simmer/rust-build-a-simple-celery-like-worker-7ae90f170515?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ae90f170515</guid>
            <category><![CDATA[task-management]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 14:29:34 GMT</pubDate>
            <atom:updated>2024-10-20T14:29:44.855Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll show you how to implement a simple Celery-like worker in Rust to handle tasks on a separate thread, relieving the load on your main thread.</p><h3>Introduction</h3><p>Recently, I needed to create long-running tasks, execute them in parallel, limit the number of tasks running simultaneously, and revoke them on demand. Unfortunately, I couldn’t find a Rust crate that supported all these features. While there’s <a href="https://github.com/rusty-celery/rusty-celery">rusty-celery,</a> it doesn’t support task revocation yet. So, I decided to implement this myself.</p><p>What I came up with works, though it may not be perfectly robust. I’d love to hear your feedback! The code shared here is part of my <a href="https://github.com/thomassimmer/rocket-template">Rocket-based project template</a>. Specifically, I’ll show you how I built a worker system to send requests to an LLM (Large Language Model). The worker listens to a dedicated queue, and whenever a user posts a message, a task is sent to the worker, which generates a new message by interacting with the LLM.</p><h3>Structures needed</h3><p>First, we need a <strong>Task</strong> structure:</p><pre>use std::sync::Arc;<br><br>use crate::{db::common::ConnectionPool, models::message::Message};<br><br>use super::app_state::AppState;<br><br>pub struct Task {<br>    pub id: i32,<br>    pub message: Message,<br>    pub app_state: AppState,<br>    pub conn: Arc&lt;ConnectionPool&gt;,<br>}</pre><p>Next, we need a <strong>WorkerQueue</strong> structure:</p><pre>use std::sync::Arc;<br><br>use tokio::sync::{Mutex, Notify};<br><br>use super::task::Task;<br><br>#[derive(Clone)]<br>pub struct WorkerQueue {<br>    pub name: String,<br>    pub task_queue: Arc&lt;Mutex&lt;Vec&lt;Task&gt;&gt;&gt;,<br>    pub notifier: Arc&lt;Notify&gt;,<br>    pub max_parallel_task: u8,<br>}</pre><p>Finally, the <strong>AppState</strong> structure:</p><pre>use std::{collections::HashMap, sync::Arc};<br><br>use rocket::tokio::sync::broadcast::Sender;<br><br>use crate::models::message::Message;<br><br>use super::worker_queue::WorkerQueue;<br><br>#[derive(Clone)]<br>pub struct AppState {<br>    pub worker_queues: HashMap&lt;String, WorkerQueue&gt;,<br>    pub message_sender: Arc&lt;Sender&lt;Message&gt;&gt;,<br>}</pre><h3>Changes in the Rocket App Creation</h3><p>In the Rocket app setup, we initialize the worker queues for each LLM, start a message channel for WebSocket communication, and initialize the application state. For each queue, we spawn a worker to process tasks:</p><pre>#[launch]<br>pub fn rocket() -&gt; _ {<br>    let worker_queues: HashMap&lt;String, WorkerQueue&gt; = HashMap::from([<br>        (<br>            &quot;gpt-4-32k&quot;.to_string(),<br>            WorkerQueue {<br>                name: &quot;gpt-4-32k&quot;.to_string(),<br>                task_queue: Arc::new(Mutex::new(Vec::new())),<br>                notifier: Arc::new(Notify::new()),<br>                max_parallel_task: 2,<br>            },<br>        ),<br>        (<br>            &quot;gpt-4o&quot;.to_string(),<br>            WorkerQueue {<br>                name: &quot;gpt-4o&quot;.to_string(),<br>                task_queue: Arc::new(Mutex::new(Vec::new())),<br>                notifier: Arc::new(Notify::new()),<br>                max_parallel_task: 2,<br>            },<br>        ),<br>    ]);<br><br>    let message_sender = Arc::new(channel::&lt;Message&gt;(1024).0);<br>    let app_state = AppState {<br>        worker_queues: worker_queues.clone(),<br>        message_sender,<br>    };<br><br>    for queue in worker_queues.values() {<br>        spawn(worker(queue.clone()));<br>    }<br><br>    rocket::build()<br>        .manage(app_state)<br>        .mount(&quot;/&quot;, routes::home::get_routes())<br>        .mount(&quot;/users&quot;, routes::user::get_routes())<br>        .mount(&quot;/messages&quot;, routes::message::get_routes())<br>        .mount(&quot;/static&quot;, FileServer::from(relative!(&quot;src/static&quot;)))<br>        .mount(&quot;/ws/&quot;, routes![events])<br>        .register(&quot;/&quot;, catchers![routes::home::not_found])<br>        .attach(cors_fairing())<br>        .attach(ConnectionPool::fairing())<br>        .attach(AdHoc::on_ignite(&quot;Diesel Migrations&quot;, run_migrations))<br>}</pre><h3>Writing the worker</h3><p>Here’s the worker, which runs in an infinite loop. It waits for notifications that a task is available, processes tasks, and ensures the maximum number of parallel tasks is not exceeded:</p><pre>use std::{sync::Arc, thread, time::Duration};<br><br>use chrono::Utc;<br>use tokio::{sync::Mutex, task};<br><br>use crate::{<br>    db,<br>    models::message::Message,<br>    structs::{task::Task, worker_queue::WorkerQueue},<br>};<br><br>pub async fn worker(queue: WorkerQueue) {<br>    // Counter to track running tasks<br>    let task_running = Arc::new(Mutex::new(0));<br><br>    loop {<br>        // Wait for notification<br>        queue.notifier.notified().await;<br><br>        loop {<br>            // Lock and check the queue for tasks<br>            let task_opt = {<br>                let mut queue = queue.task_queue.lock().await;<br>                queue.pop()<br>            };<br><br>            let mut task_running_lock = task_running.lock().await;<br><br>            if let Some(task) = task_opt {<br>                // Only process the task if we haven&#39;t reached the max number of parallel tasks<br>                if *task_running_lock &lt; queue.max_parallel_task {<br>                    *task_running_lock += 1;<br><br>                    let task_running_clone = task_running.clone(); // Clone the counter for use in the async block<br><br>                    // Spawn an asynchronous task<br>                    task::spawn(async move {<br>                        process_task(task).await; // Process the task<br><br>                        // Decrement the task counter when the task completes<br>                        let mut task_running_lock = task_running_clone.lock().await;<br>                        *task_running_lock -= 1;<br>                    });<br>                } else {<br>                    // If we&#39;ve reached the max parallel tasks, just break out of the loop<br>                    break;<br>                }<br>            } else {<br>                // If there&#39;s no task left in the queue, break<br>                break;<br>            }<br>        }<br>    }<br>}<br><br>pub async fn process_task(task: Task) {<br>    // This function simulates the action of invoking the OpenAI API<br>    // to get a response from ChatGPT to the given message.<br><br>    println!(&quot;Starting to process task {}...&quot;, task.id);<br><br>    // Wait 1 second to simulate ChatGPT latency<br>    thread::sleep(Duration::from_secs(1));<br><br>    let message = Message {<br>        id: None,<br>        content: &quot;Content generated by ChatGPT&quot;.to_string(),<br>        creation_date: Utc::now().naive_utc(),<br>        author_id: 1000, // Fake id for ChatGPT<br>    };<br><br>    db::message::create_message(&amp;task.conn, message).await;<br><br>    println!(&quot;Finished processing task {}.&quot;, task.id);<br>}</pre><h3>Sending Tasks</h3><p>Here’s the logic to create a new message:</p><pre>pub async fn create_message(<br>    conn: ConnectionPool,<br>    new_message: InputMessage,<br>    user_id: i32,<br>    app_state: &amp;AppState,<br>) {<br>    let conn = Arc::new(conn);<br>    let message = Message {<br>        id: None,<br>        content: new_message.content,<br>        creation_date: Utc::now().naive_utc(),<br>        author_id: user_id,<br>    };<br><br>    let message = db::message::create_message(&amp;conn, message).await;<br><br>    let _ = app_state.message_sender.send(message.clone());<br><br>    create_chatgpt_user_if_not_existing(&amp;conn).await;<br>    message.send_task_to_worker(conn, app_state.clone()).await;<br>}</pre><p>The <strong>Message</strong> struct has the <strong>send_task_to_worker</strong> method:</p><pre>pub async fn send_task_to_worker(&amp;self, conn: Arc&lt;ConnectionPool&gt;, app_state: AppState) {<br>    if let Some(id) = self.id {<br>        let task = Task {<br>            id,<br>            message: self.clone(),<br>            app_state: app_state.clone(),<br>            conn,<br>        };<br><br>        {<br>            let queue = app_state.worker_queues.get(&quot;gpt-4o&quot;).unwrap();<br>            let mut task_queue = queue.task_queue.lock().await;<br>            task_queue.insert(0, task);<br>            queue.notifier.notify_one();<br>        }<br>    }<br>}</pre><p>This creates a Task, inserts it into the appropriate queue, and notifies the worker to start processing.</p><h3>Revoking Tasks</h3><p>To revoke tasks, you can remove them from the queue using this function:</p><pre>pub async fn revoke_task(id: i32, queue: &amp;WorkerQueue) {<br>    let mut task_queue = queue.task_queue.lock().await;<br><br>    if let Some(pos) = task_queue.iter().position(|task| task.id == id) {<br>        task_queue.remove(pos);<br>        println!(&quot;Task {} at position {} revoked.&quot;, id, pos);<br>    }<br>}</pre><p>The <strong>id</strong> is the Message ID that triggers a response from ChatGPT.</p><h3>Difficulties</h3><p>The main difficulty I encountered was testing. I had to rely on <strong>println!</strong> statements to verify behavior. If you have ideas on better ways to test this kind of system, I’d love to hear them.</p><h3>Conclusion</h3><p>I hope this article inspires you for your projects. Feel free to leave comments, as I’m always curious to hear your thoughts on my work.</p><p>Thank you for reading,</p><p>Thomas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*d73uj0hnEV1dDEnO" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ae90f170515" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Cross-Platform App with Flutter and Rust: Locale Selection]]></title>
            <link>https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-locale-selection-1fb318224129?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb318224129</guid>
            <category><![CDATA[actix-web]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[translation]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 17:33:26 GMT</pubDate>
            <atom:updated>2025-11-14T13:59:12.209Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Introduction</strong></h4><p>In this article, I’ll walk you through how I implemented locale selection for a cross-platform app using Flutter for the frontend and Actix for the backend. We’ll cover everything from the screen where the locale is selected to the process of updating the application’s locale, including interactions with the API.</p><p>For more context, feel free to check out <a href="https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-a-beginners-journey-92cbb893c2f9">the first article</a> of this series.</p><h4><strong>1. How is the locale selected in Flutter?</strong></h4><p>First things first, where is the locale defined in the app? Let’s start with the app’s entry point in <strong>main.dart</strong>:</p><pre>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await dotenv.load();<br><br>  setupServiceLocator();<br>  runApp(FlutterActixApp());<br>}</pre><p>Next, let’s take a look at <strong>FlutterActixApp</strong> in <strong>core/app.dart</strong>:</p><pre>class FlutterActixApp extends StatelessWidget {<br>  const FlutterActixApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MultiBlocProvider(<br>        providers: _createBlocProviders(),<br>        child:<br>            BlocBuilder&lt;ProfileBloc, ProfileState&gt;(builder: (context, state) {<br>          Locale locale =<br>              Locale(Platform.localeName); // device locale by default<br><br>          final Brightness brightness =<br>              MediaQuery.of(context).platformBrightness;<br>          ThemeData themeData = brightness == Brightness.dark<br>              ? DarkAppTheme().themeData<br>              : LightAppTheme().themeData;<br><br>          if (state.profile != null) {<br>            locale = Locale(state.profile!.locale);<br>            themeData = state.profile!.theme == &#39;dark&#39;<br>                ? DarkAppTheme().themeData<br>                : LightAppTheme().themeData;<br>          }<br><br>          return MaterialApp.router(<br>            debugShowCheckedModeBanner: false,<br>            routerConfig: router,<br>            locale: locale,<br>            theme: themeData,<br>            localizationsDelegates: AppLocalizations.localizationsDelegates,<br>            supportedLocales: AppLocalizations.supportedLocales,<br>          );<br>        }));<br>  }<br><br>  ...<br>}</pre><p>As you can see, the app initially uses the device’s locale and theme. However, if a profile exists (i.e., if the user is authenticated), it retrieves the saved locale and theme from the user’s profile.</p><p>PS: This <strong>FlutterActixApp</strong> class also defines the method <strong>_createBlocProviders</strong>, which initializes the blocs.</p><h4><strong>2. From selecting a locale to calling the API</strong></h4><p>Let’s now look at the screen where the user can select a different locale, in <strong>features/profile/presentation/screens/language_selection_screen.dart</strong>:</p><pre>class LocaleSelectionScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(AppLocalizations.of(context)!.selectLanguage),<br>      ),<br>      body: BlocBuilder&lt;ProfileBloc, ProfileState&gt;(<br>        builder: (context, state) {<br>          if (state is ProfileAuthenticated) {<br>            return _buildLocaleSelectionView(context, state);<br>          } else if (state is ProfileLoading) {<br>            return Center(child: CircularProgressIndicator());<br>          } else {<br>            return Center(<br>                child: Text(AppLocalizations.of(context)!.failedToLoadProfile));<br>          }<br>        },<br>      ),<br>    );<br>  }<br><br>  Widget _buildLocaleSelectionView(<br>      BuildContext context, ProfileAuthenticated state) {<br>    final List&lt;Map&lt;String, String&gt;&gt; locales = [<br>      {&#39;code&#39;: &#39;en&#39;, &#39;name&#39;: &#39;English&#39;},<br>      {&#39;code&#39;: &#39;fr&#39;, &#39;name&#39;: &#39;Français&#39;},<br>    ];<br><br>    return Column(<br>        children: locales.map((locale) {<br>      return ListTile(<br>        title: Text(locale[&#39;name&#39;]!),<br>        leading: Radio&lt;String&gt;(<br>          value: locale[&#39;code&#39;]!,<br>          groupValue: state.profile.locale,<br>          onChanged: (String? value) {<br>            BlocProvider.of&lt;ProfileBloc&gt;(context)<br>                .add(ProfileUpdateLocaleEvent(locale: value!));<br>          },<br>        ),<br>      );<br>    }).toList());<br>  }<br>}</pre><p>This screen provides a simple interface for selecting the language:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nL952qz3RI2w1YPlhsh3ZQ.png" /></figure><p>In case you’re wondering about the blue header and navigation bar, it’s because this screen is a child of <strong>RootScreen</strong>, defined in <strong>core/presentation/screens/root_screen.dart</strong>. Feel free to explore it in <strong>core/router.dart</strong> to see how it’s used.</p><p>So, when the user selects a locale, it triggers an event with:</p><pre>BlocProvider.of&lt;ProfileBloc&gt;(context)<br>            .add(ProfileUpdateLocaleEvent(locale: value!));</pre><p>The event is defined in <strong>features/profile/presentation/blocs/profile_events.dart</strong>:</p><pre>class ProfileUpdateLocaleEvent extends ProfileEvent {<br>  final String locale;<br><br>  const ProfileUpdateLocaleEvent({<br>    required this.locale,<br>  });<br><br>  @override<br>  List&lt;Object&gt; get props =&gt; [locale];<br>}</pre><p>This event is handled by the <strong>ProfileBloc</strong>:</p><pre>class ProfileBloc extends Bloc&lt;ProfileEvent, ProfileState&gt; {<br>  ...<br>  final PostProfileUsecase postProfileUsecase =<br>      GetIt.instance&lt;PostProfileUsecase&gt;();<br>  ...<br><br>  ProfileBloc({required this.authBloc}) : super(ProfileLoading()) {<br>    ...<br>    on&lt;ProfileUpdateLocaleEvent&gt;(_updateLocale);<br>    ...<br><br>    Future&lt;void&gt; _updateLocale(<br>      ProfileUpdateLocaleEvent event, Emitter&lt;ProfileState&gt; emit) async {<br>        final currentState = state as ProfileAuthenticated;<br><br>        emit(ProfileLoading(profile: state.profile));<br><br>        Profile profile = currentState.profile;<br>        profile.locale = event.locale;<br><br>        final result = await postProfileUsecase.call(profile);<br><br>        result.fold((error) {<br>        if (error is ShouldLogoutError) {<br>            authBloc.add(AuthLogoutEvent(message: ErrorMessage(error.messageKey)));<br>        } else {<br>            emit(ProfileAuthenticated(<br>            profile: currentState.profile,<br>            message: ErrorMessage(error.messageKey),<br>            ));<br>        }<br>        },<br>            (profile) =&gt; emit(ProfileAuthenticated(<br>                profile: profile,<br>                message: SuccessMessage(&#39;profileUpdateSuccessful&#39;))));<br>    }<br>    ...<br>  }<br>}</pre><p>When a user selects a locale, the app emits a <strong>ProfileLoading</strong> state, keeping the current profile data (locale, theme, etc.). It then calls the responsible use case. Depending on the outcome, it either emits a <strong>ProfileAuthenticated </strong>state with updated information or an error/success message, or disconnects the user if a <strong>ShouldLogoutError</strong> occurs.</p><p>The <strong>postProfileUsecase.call(profile)</strong> method is straightforward:</p><pre>class PostProfileUsecase {<br>  final ProfileRepository profileRepository;<br><br>  PostProfileUsecase(this.profileRepository);<br><br>  Future&lt;Either&lt;DomainError, Profile&gt;&gt; call(Profile profile) async {<br>    return await profileRepository.postProfileInformation(profile);<br>  }<br>}</pre><p>This could include additional validations, but for now, it simply forwards the request to the profile repository’s <strong>postProfileInformation</strong> method.</p><p>The <strong>ProfileRepository</strong> interface is defined in <strong>features/profile/domain/repositories/profile_repository.dart</strong>:</p><pre>abstract class ProfileRepository {<br>  ...<br>  Future&lt;Either&lt;DomainError, Profile&gt;&gt; postProfileInformation(Profile profile);<br>  ...<br>}</pre><p>Its implementation is in <strong>features/profile/data/repositories/profile_repository_impl.dart</strong>:</p><pre>class ProfileRepositoryImpl implements ProfileRepository {<br>  final ProfileRemoteDataSource remoteDataSource;<br>  final logger = Logger();<br><br>  ProfileRepositoryImpl(this.remoteDataSource);<br><br>  ...<br>  @override<br>  Future&lt;Either&lt;DomainError, Profile&gt;&gt; postProfileInformation(<br>      Profile profile) async {<br>    try {<br>      final profileModel = await remoteDataSource.postProfileInformation(<br>          UpdateProfileRequestModel(<br>              username: profile.username,<br>              locale: profile.locale,<br>              theme: profile.theme));<br><br>      return Right(Profile(<br>          username: profileModel.username,<br>          locale: profileModel.locale,<br>          theme: profileModel.theme,<br>          otpBase32: profileModel.otpBase32,<br>          otpAuthUrl: profileModel.otpAuthUrl,<br>          otpVerified: profileModel.otpVerified,<br>          passwordIsExpired: profileModel.passwordIsExpired));<br>    } on ParsingError {<br>      logger.e(&#39;ParsingError occurred.&#39;);<br>      return Left(InvalidResponseDomainError());<br>    } on UnauthorizedError {<br>      logger.e(&#39;UnauthorizedError occurred.&#39;);<br>      return Left(UnauthorizedDomainError());<br>    } on InvalidRefreshTokenError {<br>      logger.e(&#39;InvalidRefreshTokenError occured.&#39;);<br>      return Left(InvalidRefreshTokenDomainError());<br>    } on RefreshTokenNotFoundError {<br>      logger.e(&#39;RefreshTokenNotFoundError occured.&#39;);<br>      return Left(RefreshTokenNotFoundDomainError());<br>    } on RefreshTokenExpiredError {<br>      logger.e(&#39;RefreshTokenExpiredError occured.&#39;);<br>      return Left(RefreshTokenExpiredDomainError());<br>    } on InternalServerError {<br>      logger.e(&#39;InternalServerError occured.&#39;);<br>      return Left(InternalServerDomainError());<br>    } catch (e) {<br>      logger.e(&#39;Data error occurred: ${e.toString()}&#39;);<br>      return Left(UnknownDomainError());<br>    }<br>  }<br>  ...<br>}</pre><p>This method calls <strong>remoteDataSource</strong> to make the API request via <strong>postProfileInformation</strong>, which passes the request model <strong>UpdateProfileRequestModel</strong>. Depending on the outcome, the function either returns the updated profile or logs and converts any data errors into domain errors.</p><p>Now, let’s take a look at <strong>ProfileRemoteDataSource</strong>, located in <strong>features/profile/data/sources/remote_data_sources.dart</strong>:</p><pre>class ProfileRemoteDataSource {<br>  final InterceptedClient apiClient;<br>  final String baseUrl;<br><br>  ProfileRemoteDataSource({required this.apiClient, required this.baseUrl});<br>  ...<br>  Future&lt;ProfileModel&gt; postProfileInformation(<br>      UpdateProfileRequestModel profile) async {<br>    final url = Uri.parse(&#39;$baseUrl/users/me&#39;);<br>    final response = await apiClient.post(<br>      url,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>      body: json.encode(profile.toJson()),<br>    );<br><br>    final jsonBody = json.decode(response.body);<br><br>    if (response.statusCode == 200) {<br>      try {<br>        return ProfileModel.fromJson(jsonBody[&#39;user&#39;]);<br>      } catch (e) {<br>        throw ParsingError();<br>      }<br>    }<br><br>    if (response.statusCode == 401) {<br>      throw UnauthorizedError();<br>    }<br><br>    if (response.statusCode == 500) {<br>      throw InternalServerError();<br>    }<br><br>    throw UnknownError();<br>  }<br>  ...<br>}</pre><p>I am using an instance of <strong>InterceptedClient</strong> to pass in the access token and retry the request if it gets expired. This way, the client can refresh it and retry the operation seamlessly.</p><p>Once the request is made, I attempt to decode the response. If decoding fails, I raise a <strong>ParsingError</strong> from the data layer. If the request returns a different status code, I handle it accordingly by throwing the corresponding error.</p><h4><strong>3. On the backend side</strong></h4><p>The entry point of the API is the <strong>src/main.rs</strong> file, where an instance of <strong>Application</strong> is created. This initializes a server running the result of the <strong>create_app</strong> function:</p><pre>pub fn create_app(<br>    connection_pool: Pool&lt;Postgres&gt;,<br>    secret: String,<br>    token_cache: TokenCache,<br>) -&gt; App&lt;...&gt; {<br>    // Initialize repositories (Infrastructure Layer)<br>    let profile_user_repo_impl = ProfileUserRepositoryImpl::new(connection_pool.clone());<br><br>    // Initialize use cases (Application Layer)<br>    let update_profile_use_case = UpdateProfileUseCase::new(<br>        Box::new(profile_user_repo_impl.clone()),<br>    );<br><br>    App::new()<br>        .service(<br>            web::scope(&quot;/api&quot;)<br>                ...<br>                .service(<br>                    web::scope(&quot;/users&quot;)<br>                        // Scope without middleware applied to routes that don&#39;t need it<br>                        .service(is_otp_enabled)<br>                        // Nested scope with middleware for protected routes<br>                        .service(<br>                            web::scope(&quot;&quot;)<br>                                .wrap(TokenValidator {})  // Middleware validates tokens<br>                                .service(update_profile)  // Controller from Presentation Layer<br>                                ...<br>                        ),<br>                ),<br>        )<br>        ...<br>        .app_data(web::Data::new(connection_pool))<br>        .app_data(web::Data::new(secret))<br>        .app_data(web::Data::new(token_cache))<br>        // Inject use cases via web::Data<br>        .app_data(web::Data::new(update_profile_use_case))<br>}</pre><p>This function sets up the routes, dependency injection, and state variables for the API. The <strong>update_profile</strong> controller is located in <strong>features/profile/presentation/controllers/profile_controller.rs</strong> and handles updating user profile data:</p><pre>#[post(&quot;/me&quot;)]<br>pub async fn update_profile(<br>    request_claims: ReqData&lt;Claims&gt;,  // Claims extracted by middleware<br>    body: web::Json&lt;UpdateProfileRequest&gt;,<br>    use_case: web::Data&lt;UpdateProfileUseCase&gt;,<br>) -&gt; impl Responder {<br>    match use_case.execute(request_claims.user_id, body.into_inner()).await {<br>        Ok(response) =&gt; HttpResponse::Ok().json(response),<br>        Err(e) =&gt; {<br>            error!(&quot;Update profile error: {}&quot;, e);<br>            let error_response = match e {<br>                ProfileDomainError::UserNotFound =&gt; GenericResponse {<br>                    code: &quot;USER_NOT_FOUND&quot;.to_string(),<br>                    message: &quot;User not found&quot;.to_string(),<br>                },<br>                _ =&gt; GenericResponse {<br>                    code: &quot;PROFILE_UPDATE_ERROR&quot;.to_string(),<br>                    message: &quot;Failed to update profile&quot;.to_string(),<br>                },<br>            };<br>            HttpResponse::InternalServerError().json(error_response)<br>        }<br>    }   <br>}</pre><p>The process here follows clean architecture principles:</p><p>1. <strong>Presentation Layer</strong>: The controller receives `Claims` from the middleware via `ReqData&lt;Claims&gt;` and extracts the `user_id`<br>2. <strong>Application Layer</strong>: The controller calls the use case with the `user_id` and request DTO<br>3. <strong>Use Case</strong>: The `UpdateProfileUseCase` orchestrates domain entities and repositories<br>4. <strong>Infrastructure Layer</strong>: The repository implementation handles database operations<br>5. <strong>Error Mapping</strong>: Domain errors are mapped to HTTP responses in the controller</p><p>You might be wondering how the `Claims` parameter made its way into my function:</p><pre>request_claims: ReqData&lt;Claims&gt;</pre><p>This is made possible by the <strong>TokenValidator</strong> middleware, which extracts the access token from the request, validates it, and stores the `Claims` in request extensions. The middleware is defined in <strong>core/middlewares/token_validator.rs</strong>. Here’s the essential part of it:</p><pre><br>impl&lt;S, B&gt; Service&lt;ServiceRequest&gt; for TokenValidatorMiddleware&lt;S&gt;<br>where<br>    S: Service&lt;ServiceRequest, Response = ServiceResponse&lt;B&gt;, Error = Error&gt; + &#39;static,<br>    S::Future: &#39;static,<br>    B: &#39;static,<br>{<br>    // ... implementation details ...<br><br>    fn call(&amp;self, req: ServiceRequest) -&gt; Self::Future {<br>        let service = Rc::clone(&amp;self.service);<br>        let secret = req.app_data::&lt;Data&lt;String&gt;&gt;().unwrap().to_string();<br>        let pool = req.app_data::&lt;Data&lt;PgPool&gt;&gt;().unwrap().clone();<br>        let cached_tokens = req.app_data::&lt;Data&lt;TokenCache&gt;&gt;().unwrap().clone();<br><br>        Box::pin(async move {<br>            match retrieve_claims_for_token(req.request().clone(), secret) {<br>                Ok(claims) =&gt; {<br>                    // Validate token expiration<br>                    if now() &gt; DateTime::&lt;Utc&gt;::from_timestamp(claims.exp, 0).unwrap() {<br>                        return Ok(req.into_response(<br>                            HttpResponse::Unauthorized()<br>                                .json(AppError::AccessTokenExpired.to_response())<br>                                .map_into_right_body(),<br>                        ));<br>                    }<br><br>                    // Check cache, then database if needed<br>                    let last_activity = cached_tokens.get_value_for_key(claims.jti).await;<br>                    if last_activity.is_none() {<br>                        // Verify token exists in database (could have been revoked)<br>                        let existing_token = get_user_token(&amp;**pool, claims.user_id, claims.jti).await;<br>                        match existing_token {<br>                            Ok(Some(_)) =&gt; {<br>                                cached_tokens.update_or_insert_key(claims.jti, now()).await;<br>                            }<br>                            Ok(None) =&gt; {<br>                                return Ok(req.into_response(<br>                                    HttpResponse::Unauthorized()<br>                                        .json(AppError::InvalidAccessToken.to_response())<br>                                        .map_into_right_body(),<br>                                ));<br>                            }<br>                            Err(_) =&gt; {<br>                                return Ok(req.into_response(<br>                                    HttpResponse::InternalServerError()<br>                                        .json(AppError::DatabaseQuery.to_response())<br>                                        .map_into_right_body(),<br>                                ));<br>                            }<br>                        }<br>                    };<br><br>                    // Store Claims in request extensions for ReqData extractor<br>                    req.extensions_mut().insert(claims);<br>                    let res = service.call(req).await?;<br>                    Ok(res.map_into_left_body())<br>                }<br>                Err(_) =&gt; Ok(req.into_response(<br>                    HttpResponse::Unauthorized()<br>                        .json(AppError::InvalidAccessToken.to_response())<br>                        .map_into_right_body(),<br>                )),<br>            }<br>        })<br>    }<br>}</pre><p>In essence, the middleware validates the token, checks the cache and database if needed, and stores the `Claims` (containing `user_id`, `is_admin`, etc.) in request extensions. Controllers then extract `Claims` using `ReqData&lt;Claims&gt;` instead of the full `User` object. This optimization reduces database queries and follows clean architecture principles by keeping the presentation layer focused on HTTP concerns while business logic resides in the use cases.</p><h4><strong>4. Where and how do I write my translations in Flutter?</strong></h4><p>Now that we’ve covered how the locale is updated both on the backend and in the frontend, let’s take a look at how this locale is used to handle translations in the app.</p><p>You may have already noticed from the earlier code snippets that I often use something like this:</p><pre>appBar: AppBar(<br>  title: Text(AppLocalizations.of(context)!.selectLanguage),<br>),</pre><p>In this case, Flutter retrieves the corresponding entry from <strong>lib/l10n/app_en.arb</strong> if the locale is set to <strong>“en”</strong>, or from <strong>lib/l10n/app_fr.arb</strong> if the locale is <strong>“fr”</strong>. These files look like:</p><pre>{<br>  &quot;@@locale&quot;: &quot;en&quot;,<br>  &quot;alreadyAnAccountLogin&quot;: &quot;Already have an account? Sign in&quot;,<br>  &quot;about&quot;: &quot;About&quot;,<br>  ...<br>}</pre><p>But how do I handle translations for dynamic error and success messages? I found a neat solution by creating a <strong>GlobalSnackBar</strong> component:</p><pre>class GlobalSnackBar {<br>  static Color _getBackgroundColor(BuildContext context, Message message) {<br>    if (message is SuccessMessage) {<br>      return context.colors.accent;<br>    } else if (message is InfoMessage) {<br>      return context.colors.information;<br>    } else {<br>      return context.colors.error;<br>    }<br>  }<br><br>  static show(<br>    BuildContext context,<br>    Message? message,<br>  ) {<br>    if (message == null) {<br>      return null;<br>    }<br><br>    final messageTranslated = getTranslatedMessage(context, message);<br>    final backgroundColor = _getBackgroundColor(context, message);<br><br>    return (ScaffoldMessenger.of(context).showSnackBar(<br>      SnackBar(<br>        content: Text(messageTranslated),<br>        backgroundColor: backgroundColor,<br>        duration: Duration(seconds: 3),<br>        showCloseIcon: true,<br>        behavior: SnackBarBehavior.floating,<br>        shape: RoundedRectangleBorder(<br>          borderRadius: BorderRadius.circular(5.0),<br>        ),<br>        closeIconColor: context.colors.text,<br>      ),<br>    ));<br>  }<br>}</pre><p>I can then call this component inside my screens like this:</p><pre>...<br>@override<br>Widget build(BuildContext context) {<br>  return BlocListener&lt;AuthBloc, AuthState&gt;(<br>    listener: (context, state) {<br>      GlobalSnackBar.show(context, state.message);<br>    }<br>    ...<br>  )<br>}</pre><p>This way, I can customize the appearance of the snack bar based on the type of message (error, success, info) and easily translate the message using <strong>getTranslatedMessage</strong>, which is defined in <strong>core/messages/message_mapper.dart</strong>:</p><pre>String getTranslatedMessage(BuildContext context, Message message) {<br>  final localizations = AppLocalizations.of(context)!;<br><br>  if (message is ErrorMessage) {<br>    switch (message.messageKey) {<br>      // Generic<br>      case &#39;unknown_error&#39;:<br>        return localizations.unknownError;<br>      ...<br><br>      // Auth<br>      case &#39;invalidUsernameOrCodeOrRecoveryCodeError&#39;:<br>        return localizations.invalidUsernameOrCodeOrRecoveryCodeError;<br>      ...<br><br>      // Profile<br>      case &#39;passwordNotExpiredError&#39;:<br>        return localizations.passwordNotExpiredError;<br>      ...<br>    }<br>  } else if (message is SuccessMessage) {<br>    switch (message.messageKey) {<br>      // Auth<br>      case &#39;loginSuccessful&#39;:<br>        return localizations.loginSuccessful;<br>      ...<br><br>      // Profile<br>      case &#39;passwordUpdateSuccessful&#39;:<br>        return localizations.passwordUpdateSuccessful;<br>      ...<br>    }<br>  } else if (message is InfoMessage) {<br>    switch (message.messageKey) {<br>      // Auth<br>      case &#39;recoveryCodesCopied&#39;:<br>        return localizations.recoveryCodesCopied;<br>      ...<br>    }<br>  } else {<br>    return localizations.defaultError;<br>  }<br>}</pre><p>While this solution works well, having all the messages in a single file isn’t the <strong>cleanest</strong> approach. If you have any suggestions for improvement, I’d love to hear them!</p><p>And that wraps up this article! I hope it provided some clarity. Feel free to reach out if you have any questions or need further details on this project.</p><p>Thanks for reading,</p><p>Thomas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBbfR60IQYUX8mZW81oWoA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb318224129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Cross-Platform App with Flutter and Rust: Writing Integration Tests]]></title>
            <link>https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-writing-integration-tests-b018d472c19a?source=rss-385c36f28144------2</link>
            <guid isPermaLink="false">https://medium.com/p/b018d472c19a</guid>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[actix]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[sqlx]]></category>
            <dc:creator><![CDATA[Thomas Simmer]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 10:32:53 GMT</pubDate>
            <atom:updated>2025-11-14T13:37:12.709Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>In this article, I’ll walk you through how I wrote integration tests for a cross-platform app built using Flutter for the frontend and Actix for the backend. The app has several key features, including:</p><p>1. A login/signup page using a username and password (without email, for privacy).</p><p>2. A recovery code page for new users.</p><p>3. A 2FA setup page using OTP with an external app like Google Authenticator.</p><p>4. A main app view with four tabs.</p><p>5. A profile tab where users can change settings like language, theme, 2FA and logout.</p><p>6. An account recovery page for users who lose access to 2FA or their password.</p><p>For more context, feel free to check out <a href="https://medium.com/@thomas.simmer/building-a-cross-platform-app-with-flutter-and-rust-a-beginners-journey-92cbb893c2f9">the first article</a> of this series.</p><p>My API uses these crates:</p><ul><li><strong>actix-web</strong> for managing routes, running the server, and writing tests.</li><li><strong>sqlx</strong> for safe asynchronous database queries.</li><li><strong>jsonwebtoken</strong> to handle token creation and decoding.</li><li><strong>argon2</strong> for secure password hashing.</li><li><strong>secrecy</strong> to safeguard sensitive data.</li><li><strong>totp-rs</strong> to generate and validate one-time passwords (OTPs).</li></ul><h3><strong>Goals of the Integration Tests</strong></h3><p>I needed to ensure the API handled these user actions seamlessly:</p><ul><li>Sign up using a username and password.</li><li>Receive recovery codes upon registration, as we don’t use email.</li><li>Recover access using recovery codes in case of password or 2FA loss.</li><li>Enable 2FA after registration by scanning a QR code and verifying it with an OTP.</li><li>Verify OTP on every login if 2FA is enabled.</li><li>Manage profile settings (language, theme, and 2FA) from a profile page.</li><li>Maintain secure sessions with an access token (expires in 15 minutes) and a refresh token (expires in 7 days).</li></ul><p>The integration tests needed to ensure not only that these actions were possible but also that improper usage was prevented.</p><h3><strong>Challenges in Writing Integration Tests</strong></h3><h4>1. Handling Concurrency</h4><p>A common issue with API integration tests is test concurrency. When running tests with <strong>cargo test</strong>, Rust runs tests in parallel, leading to potential conflicts if multiple tests query the same database simultaneously. These conflicts can cause random test failures.</p><p>One solution is to use database transactions for each test and roll them back afterward. While this works well in simple cases, it becomes challenging when your test involves state variables, such as a shared <strong>database connection pool</strong>.</p><p>Another approach is to use a separate database instance for each test. Ideally, this would be an in-memory database to avoid manual cleanup. Unfortunately, PostgreSQL doesn’t support in-memory databases, so this method is only viable with SQLite.</p><p>Inspired by <a href="https://www.lpalmieri.com/posts/2020-08-31-zero-to-production-3-5-html-forms-databases-integration-tests/#3-2-choosing-a-database-crate">zero2prod</a>, I opted to create a new PostgreSQL database for each test, using a unique UUID as the database name to avoid conflicts. Each test creates its own database, sets up a connection pool, runs the necessary migrations, and proceeds to execute.</p><h4>2. Controlling Time in Tests</h4><p>Another challenge arises when controlling time-sensitive logic, such as expiring tokens, in your tests. Rust’s <strong>chrono::Utc::now</strong> doesn’t provide an easy way to “freeze” time during tests, like <strong>Python’s freezegun</strong>.</p><p>Fortunately, there’s a pull request in the works on <a href="https://github.com/chronotope/chrono/pull/1244/files">chrono’s GitHub</a> that introduces the <strong>OVERRIDE_NOW</strong> variable, allowing you to override the current time on a per-thread basis. Here’s the relevant part of the PR:</p><pre>// Value to use for `Utc::now()` and `Local::now()`, when set with `Local::override_now`.<br>#[cfg(all(feature = &quot;clock&quot;, feature = &quot;test-override&quot;))]<br>thread_local!(<br>    pub(super) static OVERRIDE_NOW: RefCell&lt;Option&lt;DateTime&lt;FixedOffset&gt;&gt;&gt; = RefCell::new(None)<br>);</pre><p>With <strong>OVERRIDE_NOW</strong>, you can mock the current time in your tests without affecting other tests. By creating a custom now function, you can either use the overridden time (if set) or fall back to <strong>Utc::now()</strong>:</p><pre>use chrono::{DateTime, FixedOffset, Utc};<br>use std::cell::RefCell;<br><br>// To override the time. Needed for tests.<br>pub fn override_now(datetime: Option&lt;DateTime&lt;FixedOffset&gt;&gt;) {<br>    OVERRIDE_NOW.with(|o| *o.borrow_mut() = datetime)<br>}<br><br>// Function to use instead of Utc::now straight.<br>pub fn now() -&gt; DateTime&lt;Utc&gt; {<br>    if let Some(t) = OVERRIDE_NOW.with(|o| *o.borrow()) {<br>        return t.into();<br>    }<br><br>    Utc::now()<br>}</pre><p>Using this method, you can control time during tests. However, this approach doesn’t work with a server running in a separate thread, such as when using the reqwest crate for HTTP requests like zero2prod did. Instead, I rely on Actix’s test utilities, which run the app in the same thread as the test, making time control easier.</p><p>Here’s a basic example using Actix’s utilities:</p><pre>#[cfg(test)]<br>mod tests {<br>    use super::*;<br>    use actix_web::{test, web, App};<br><br>    #[actix_web::test]<br>    async fn test_index_get() {<br>        let app = test::init_service(<br>            App::new()<br>                .app_data(web::Data::new(AppState { count: 4 }))<br>                .service(index),<br>        )<br>        .await;<br>        let req = test::TestRequest::get().uri(&quot;/&quot;).to_request();<br>        let resp: AppState = test::call_and_read_body_json(&amp;app, req).await;<br><br>        assert_eq!(resp.count, 4);<br>    }<br>}</pre><p>The good news is that I didn’t need to rewrite my entire app with all the routes and <strong>web::Data</strong> variables for each test. Instead, I created a function in src/startup.rs that sets everything up using clean architecture:</p><pre>pub fn create_app(<br>    connection_pool: Pool&lt;Postgres&gt;,<br>    secret: String,<br>    token_cache: TokenCache,<br>) -&gt; App&lt;...&gt; {<br>    // Initialize repositories (Infrastructure Layer)<br>    let user_repo_impl = UserRepositoryImpl::new(connection_pool.clone());<br>    let token_repo_impl = TokenRepositoryImpl::new(connection_pool.clone());<br>    let token_service_impl = TokenServiceImpl::new(secret.as_bytes().to_vec());<br><br>    // Initialize use cases (Application Layer)<br>    let signup_use_case = SignupUseCase::new(<br>        Box::new(user_repo_impl.clone()),<br>        Box::new(token_repo_impl.clone()),<br>        Box::new(token_service_impl.clone()),<br>        secret.as_bytes().to_vec(),<br>    );<br>    // ... more use cases<br><br>    App::new()<br>        .service(<br>            web::scope(&quot;/api&quot;)<br>                .service(health_check)<br>                .service(<br>                    web::scope(&quot;/auth&quot;)<br>                        .service(signup)  // Controller from Presentation Layer<br>                        .service(login)<br>                        // ... more routes<br>                )<br>        )<br>        // Inject use cases via web::Data<br>        .app_data(web::Data::new(signup_use_case))<br>        .app_data(web::Data::new(login_use_case))<br>        // ...</pre><p>Here’s a basic test, like signing up a user:</p><pre>pub async fn user_signs_up(<br>    app: impl Service&lt;Request, Response = ServiceResponse&lt;impl MessageBody&gt;, Error = Error&gt;,<br>) -&gt; (String, String, Vec&lt;String&gt;) {<br>    let signup_request = SignupRequest {<br>        username: &quot;testusername&quot;.to_string(),<br>        password: &quot;password1_&quot;.to_string(),<br>        locale: &quot;en&quot;.to_string(),<br>        theme: &quot;dark&quot;.to_string(),<br>    };<br><br>    let req = test::TestRequest::post()<br>        .uri(&quot;/api/auth/signup&quot;)<br>        .insert_header(ContentType::json())<br>        .set_json(&amp;signup_request)  // Using DTO instead of raw JSON<br>        .to_request();<br>    let response = test::call_service(&amp;app, req).await;<br><br>    assert_eq!(201, response.status().as_u16());<br><br>    let body = test::read_body(response).await;<br>    let response: SignupResponse = serde_json::from_slice(&amp;body).unwrap();<br><br>    (response.access_token, response.refresh_token, response.recovery_codes)<br>}<br><br>#[sqlx::test]<br>async fn user_can_signup(pool: PgPool) {<br>    let app = spawn_app(pool).await;<br>    user_signs_up(&amp;app).await;<br>}</pre><p>Note that we now use the `SignupRequest` DTO from the Application Layer and `#[sqlx::test]` macro for automatic database management.</p><p>Now, if I want to test the expiration of an access token, I can control time using the previously mentioned override_now method:</p><pre>#[tokio::test]<br>async fn access_token_becomes_expired_after_15_minutes() {<br>    let app = spawn_app().await;<br><br>    let (access_token, _) = user_signs_up(&amp;app).await;<br><br>    user_has_access_to_protected_route(&amp;app, access_token.clone()).await;<br><br>    override_now(Some(<br>        (Utc::now() + Duration::new(14 * 60, 1)).fixed_offset(),<br>    ));<br><br>    // After 14 minutes, user can still access protected route<br>    user_has_access_to_protected_route(&amp;app, access_token.clone()).await;<br><br>    override_now(Some(<br>        (Utc::now() + Duration::new(15 * 60, 1)).fixed_offset(),<br>    ));<br><br>    // After 15 minutes, user cannot access protected route anymore<br>    let req = test::TestRequest::default()<br>        .uri(&quot;/api/users/me&quot;)<br>        .insert_header((header::AUTHORIZATION, format!(&quot;Bearer {}&quot;, access_token)))<br>        .to_request();<br>    let response = test::call_service(&amp;app, req).await;<br><br>    assert_eq!(401, response.status().as_u16());<br><br>    let body = test::read_body(response).await;<br>    let profile_response: GenericResponse = serde_json::from_slice(&amp;body).unwrap();<br>    let message = profile_response.message;<br><br>    assert_eq!(message, &quot;Token expired&quot;);<br>}</pre><p>And that’s it! I hope you found this useful. Feel free to leave a comment if you have any questions or thoughts.</p><p>See you in the next article,</p><p>Thomas</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZCqYWs-lrRM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZCqYWs-lrRM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZCqYWs-lrRM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eed4ac6770ed4ab81b012a921fa7aac/href">https://medium.com/media/6eed4ac6770ed4ab81b012a921fa7aac/href</a></iframe><p>This project is open-source and available here: <a href="https://github.com/thomassimmer/Flutter-Actix-App">https://github.com/thomassimmer/Flutter-Actix-App</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBbfR60IQYUX8mZW81oWoA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b018d472c19a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>