<?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 vladkens on Medium]]></title>
        <description><![CDATA[Stories by vladkens on Medium]]></description>
        <link>https://medium.com/@vladkens?source=rss-4d50a0a8b26------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RGstu_vw_cufjMILTDdejg.jpeg</url>
            <title>Stories by vladkens on Medium</title>
            <link>https://medium.com/@vladkens?source=rss-4d50a0a8b26------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:25:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vladkens/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[Wanted a Dictation App, Got Three Libraries]]></title>
            <link>https://medium.com/@vladkens/wanted-a-dictation-app-got-three-libraries-b3bfbe7dfda8?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3bfbe7dfda8</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 21:48:31 GMT</pubDate>
            <atom:updated>2026-11-14T21:48:31.796Z</atom:updated>
            <content:encoded><![CDATA[<h4>A month of work with agents on Wavo, a dictation app that grew its own speech recognition engine, UI library and packager.</h4><figure><img alt="Wavo: dictating into TextEdit, a colored recording bar at the bottom, the app&#39;s settings window on the right" src="https://cdn-images-1.medium.com/max/1024/1*y6yow5HfXlmaN5yC-x9wyQ.png" /></figure><p>I swapped my M2 MacBook with the old design for a new fanless M5 Air. A new computer feels like a clean start. So instead of dragging all my old apps and settings along, I went looking for lighter and more native alternatives. For example, I replaced VS Code with <a href="https://github.com/zed-industries/zed">Zed</a> and Chrome with <a href="https://github.com/imputnet/helium">Helium</a>.</p><p>To talk to agents, I used a dictation app called <a href="https://github.com/cjpais/Handy">Handy</a>. But I really didn&#39;t like that it&#39;s built on <a href="https://github.com/tauri-apps/tauri">Tauri</a>, and I wanted something native. I asked an agent to find an alternative, but nothing it found worked for me. So I decided to write my own.</p><p>People on X are rewriting everything in <a href="https://github.com/longbridge/gpui-kit">GPUI Kit</a> right now, so I decided to try it too. The author of Handy had also moved the speech recognition engine into a separate project called <a href="https://github.com/handy-computer/transcribe.cpp">transcribe.cpp</a>. So the task looked easy, especially with agents.</p><h3>Week 1. Picking a GUI and prototypes</h3><p>So I took GPUI Kit, the one everyone on X was hyping, and quickly built the first version of the UI with agents. It came out pretty well: the app with an open window used about 80 MB of RAM. But compiling was painfully slow. Part of it was GPUI Kit itself, and part was linking transcribe.cpp, which took about a minute on every rebuild.</p><p>I also didn&#39;t like that GPUI Kit pulls in over 400 dependencies, just like Node.js. Who knows what malware might be hiding in there? Besides, <a href="https://github.com/zed-industries/zed/tree/main/crates/gpui">GPUI</a> from Zed isn&#39;t a finished library with stable releases. So GPUI Kit depends on a dev version from the Zed repo, and the API can change at any moment. Another problem is integration with the system, like a tray icon or a native context menu. GPUI Kit doesn&#39;t have it, so all of that has to be written by hand.</p><p>I decided to look at other options in the Rust ecosystem. Back in the pre-agent era, I played with <a href="https://github.com/emilk/egui">egui</a> for UIs, and it left a good impression. It really was faster and lighter on memory, and it pulled in fewer crates. But all the native integrations still have to be written by hand, and the components need a lot of customizing to look nice.</p><p>I also tried native controls: Rust bindings to the system UI libraries (AppKit on macOS, Win32 on Windows and GTK on Linux). The idea came from another project I saw on X, <a href="https://github.com/egoist/mygo">mygo</a>, which builds native desktop UIs in Go. But in practice I had to write a huge pile of integration code and repeat it at least three times. The app looked native on each platform, but so different that some features couldn&#39;t be done properly. And that&#39;s for a dictation app, which is literally a settings menu, a list of models and a history.</p><p>The most annoying thing the whole time was rebuilding: every launch meant waiting almost a minute for transcribe.cpp to link. And I didn&#39;t really get why there should be C++ in my Rust toolchain at all. So I decided to look at what&#39;s going on inside.</p><h3>Week 2. My own speech recognition engine</h3><p>Inside transcribe.cpp there was <a href="https://github.com/ggml-org/ggml">ggml</a>, which has separate code for each GPU backend (Metal, Vulkan and CUDA). Each one needs its own tools to build. Rust has <a href="https://github.com/gfx-rs/wgpu">wgpu</a>, where shaders are written once in <a href="https://www.w3.org/TR/WGSL/">WGSL</a> and run on any GPU. And everything builds with a plain cargo build.</p><p>I got curious whether I could run at least one model on WGSL, though I had no plans to rewrite anything yet. I took <a href="https://github.com/salute-developers/GigaAM">GigaAM</a> v3, which I use most often, and made a small demo with it. To my surprise, the agent wrote the shader code easily, and the results were close to the original library.</p><p>That&#39;s when it became a challenge for me. I remembered optimizing math on the secp256k1 curve in <a href="https://github.com/vladkens/ecloop">ecloop</a> and <a href="https://vladkens.me/rmd160-simd/">optimizing RIPEMD-160</a>, and kept digging. The first model was GigaAM v3 e2e RNN-T, which outputs punctuation and capital letters. I also decided to add other models from the same family to see how hard it would be. They differ in the decoder. CTC recognizes each piece of audio on its own, while RNN-T also looks at the text it has already written, so it&#39;s more accurate but slower. Each of them also has a version with punctuation (e2e) and one without.</p><p>I dictate in two languages, Russian and English. Since adding Russian was easy, I thought English wouldn&#39;t be a problem either. NVIDIA&#39;s <a href="https://huggingface.co/nvidia/parakeet-tdt-0.6b-v2">Parakeet v2</a> is a good fit for English because it&#39;s accurate and fast. But when I started adding it, I found out that models come in different architectures, and each one needs its own compute code.</p><p>I took the models already packed into GGUF by the author of transcribe.cpp. It turned out that GGUF stores only the weights and some metadata about the model: the architecture name, layer sizes and vocabulary. The computations aren&#39;t in the file, so they have to be written by hand. That&#39;s the difference from TensorFlow or Apple&#39;s Core ML, where the model file describes a graph of operations and the runtime just executes it.</p><p>So I had to sit down and figure it out by reading and watching YouTube videos about how speech recognition models work. In short, long audio is cut into chunks (Whisper, for example, uses 30-second windows). Each chunk goes through a fast Fourier transform (FFT) and becomes a spectrogram (which frequencies sound at each moment). The encoder (a stack of neural network layers that mostly multiply matrices) takes the spectrogram and turns it into a sequence of vectors. The decoder reads them and outputs tokens (pieces of words) one step at a time, and these tokens make up the text. Most of the work is matrix multiplication in the encoder layers, and that&#39;s what the GPU computes.</p><figure><img alt="Audio becomes a spectrogram through FFT, the encoder turns it into vectors, and a CTC, RNN-T or TDT decoder outputs text" src="https://cdn-images-1.medium.com/max/1024/1*1FX17xTGaXYUiZoZRmG0gg.png" /></figure><p>Once I understood how it works, I added support for Parakeet v2. Codex wrote the first version overnight, but the code was messy, so I threw it away and rewrote it cleanly with Claude Code. In the end I got a pretty fast speech-to-text program that beat transcribe.cpp in my tests. Since I was on a roll, I right away added <a href="https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3">Parakeet v3</a>, a multilingual model from the same family (I barely had to write anything new). Right after it came <a href="https://github.com/openai/whisper">Whisper</a>, as a reference model to compare the others against.</p><p>Parakeet differs from GigaAM in plenty of ways. The model is bigger (24 layers vs 16, and each one is wider). It compresses audio twice as much (one vector per 80 ms instead of 40). It also has a different way to mark when each word was said. But the main difference is the decoder (TDT): along with each token, it predicts how many of the next audio frames it can skip.</p><p>The program was turning out so well that I decided to release it as a separate project in the style of <a href="https://github.com/ollama/ollama">ollama</a>. I named it <a href="https://github.com/vladkens/wavo">wavo</a>, kind of from WAV, and the name was free. Besides, I had needed local audio transcription before, and there was nothing good for it in the terminal. I tried <a href="https://github.com/ggml-org/whisper.cpp">whisper.cpp</a>, but it&#39;s slow and inconvenient (it has to be compiled from source, and the audio has to be cut into chunks by hand).</p><p>Before publishing, I decided to clean up the code. The <a href="https://github.com/ejmahler/RustFFT">rustfft</a> crate was still slowing down the build. People can use wavo as a library, so everyone who builds it would get that delay too. Once I found the cause, I wrote my own FFT just for this task. It came out at 176 lines of code vs 55,000 in rustfft, and rebuilds went from 11.9 down to 2.1 seconds. The crate itself is good, it&#39;s just built for every case, and I needed only one.</p><p>The last step before publishing was testing. Luckily, I have a few Macs at hand, an N100 box with Linux and an x86 machine with a GeForce card and a good CPU. I had the agent run the final tests and compare the speed with other libraries. On Macs my library crushed everyone on speed, no question (I&#39;m still shocked it was that easy). But on Windows with an NVIDIA card it was a big failure. Again I had to dig in, and it turned out there&#39;s a thing called flash attention.</p><p>Attention is the part of the model where each vector is compared with all the others in the same audio chunk. For Whisper that&#39;s 1,500 vectors per 30 seconds, so more than two million comparisons in each layer. Regular code writes this whole table to GPU memory and then reads it back. Flash attention computes the same thing in small pieces in fast memory next to the GPU cores and never stores the whole table.</p><figure><img alt="Regular attention moves the whole comparison table through GPU memory, while flash attention computes it piece by piece in fast memory" src="https://cdn-images-1.medium.com/max/1024/1*NgdZrMj6VKVMf9kENOqkSw.png" /></figure><p>On Macs, the agent had already made such shaders earlier, but for Apple&#39;s matrix units (hardware acceleration). NVIDIA&#39;s units have a different size, so on NVIDIA wavo computed everything with generic code. After I added shaders for NVIDIA&#39;s matrix units, wavo on Windows caught up with transcribe.cpp and in some cases beat it. A short Whisper turbo recording now takes 201 ms vs 226 ms for transcribe.cpp, down from 637.</p><p>I made all the measurements on an RTX 4060 and didn&#39;t test on AMD Radeon at all. So I&#39;d be glad to see results from other GPUs in <a href="https://github.com/vladkens/wavo/issues">issues</a>.</p><p>During testing I also found that on M5, wgpu uses only the old matrix units. The M5 got a <a href="https://www.apple.com/newsroom/2025/10/apple-unleashes-m5-the-next-big-leap-in-ai-performance-for-apple-silicon/">neural accelerator</a> in each GPU core, which multiplies matrices three times faster (0.60 ms vs 1.89 ms). But it&#39;s only available through Metal 4, and wgpu doesn&#39;t support it yet. I worked around this with a separate Metal shader just for M5 and opened an <a href="https://github.com/gfx-rs/wgpu/issues/10626">issue in wgpu</a>.</p><p>I also taught wavo to run on the Neural Engine (a separate part of Apple chips for neural networks), but that&#39;s another story. At the end, I ran a final comparison of Parakeet v3 in English against other engines, and the numbers looked impressive.</p><pre>Engine          Runs on        5 s phrase  1 h recording<br>--------------  -------------  ----------  -------------<br>wavo            Neural Engine      0.12 s           200×<br>FluidAudio      Neural Engine      0.13 s           175×<br>wavo            GPU                0.14 s           160×<br>transcribe.cpp  GPU                0.12 s           107×<br>parakeet.cpp    GPU                0.77 s            90×<br>parakeet-mlx    GPU                0.63 s            61×<br>sherpa-onnx     CPU                0.83 s            39×</pre><p>The table shows the time for a 5-second phrase and how many times faster than real time a one-hour recording gets transcribed (MacBook Pro on M5). In Russian with GigaAM v3 the gap is similar: wavo is 330 times faster than real time, and transcribe.cpp is 262 times faster.</p><h3>Week 3. My own renderer</h3><p>While I worked on wavo, another agent was experimenting with a UI library in the background. Every approach still needed a lot of hand-written wrappers to talk to the OS, so I decided I could write the renderer myself too. I also had some experience with UIs in video games, so the task seemed simple.</p><p>I&#39;ve long been a fan of <a href="https://www.sublimetext.com/">Sublime Text</a>, and especially <a href="https://www.sublimemerge.com/">Sublime Merge</a>, and their approach to UI. I thought that if the authors of these apps and of the Zed editor could write their own UI framework, then I, armed with an agent, could too. Armed with strings and nm, we looked at which system functions Sublime Merge uses and figured out the idea behind it. It was an interesting one ;)</p><p>The text there is drawn by the system itself (CoreText on macOS, DirectWrite on Windows, Pango on Linux), so it looks native everywhere. That&#39;s unlike egui, for example, which draws glyphs on its own. The system draws each glyph once and it goes into a cache, and after that the screen gets ready glyphs from the cache. Context menus work the same way and come from the system (GPUI Kit draws them itself by default).</p><p>So it turned into a kind of Frankenstein. The edges are system stuff, and in the middle, like the filling in a sandwich, is my library, which lays out elements in the window and builds components from them.</p><p>Rendering uses immediate mode (the frame is built from scratch every time, without a complex event system). Regular apps don&#39;t have that much interactivity, and a settings window doesn&#39;t need to be redrawn 60 or 120 times per second. Besides, the frame is rebuilt only when something changes, and an idle window draws nothing.</p><p>I decided to draw the frame itself on the CPU. It&#39;s the simplest code, and it works the same everywhere, without shaders, drivers and other junk that has to be integrated and then tested too. The finished frame goes to the system&#39;s regular 2D window output. For an app without complex animations, that&#39;s more than fast enough.</p><p>3D acceleration pulls in extra libraries, and the program starts eating more memory (on Windows a simple window with D3D11 takes 27 MB instead of 5.1). But if it&#39;s ever needed, I can always add it later.</p><p>The renderer itself came out at about 3,000 lines of Rust, and the agent quickly put together the basic components on top of it (around 6,000 more lines). Everything worked, and it seemed like the job was almost done.</p><p>Next I needed a context menu and a small popup that shows the text being dictated. That&#39;s where the pain and suffering began, especially when I ran everything on real computers with Linux and Windows instead of VMs.</p><p>Now I understand why there were so few GUI frameworks in the pre-agent era. The hard part isn&#39;t writing a renderer and a component system at all. The hard part is wiring all of it together on different platforms so that it works. Each cross-platform feature can easily take several thousand lines for three systems:</p><ul><li>windows (open them, drag them and draw in them): 5,000 lines;</li><li>text fields and IME: 4,000;</li><li>tray, hotkeys and autostart: 7,000;</li><li>accessibility on macOS: 3,000;</li><li>native context menu: 2,000.</li></ul><p>Of course the agent writes the code, but someone still has to read it, check it and test it on each system, and that&#39;s a lot of work.</p><p>For example, a context menu can be drawn by the app&#39;s own renderer, and that&#39;s how GPUI in Zed does it. But it looks janky, and more importantly, such a menu can&#39;t go outside the window. I had never thought about this before, but once I started writing, I realized it matters. Sublime Merge can do it, and I give it credit for that.</p><p>As expected, Linux was the biggest pain. On macOS and Windows everything goes through one system API, but Linux is a damn zoo. At first I tried to draw separately on X11 and Wayland to make the program as optimized as possible, but the amount of code grew exponentially. So I made a compromise and took GTK 3, which is on almost every distro. Sublime Merge does the same.</p><p>I named the library <a href="https://github.com/vladkens/nimbo">nimbo</a>. A simple <a href="https://github.com/vladkens/nimbo/blob/main/examples/counter.rs">counter window</a> built with it pulls in 14 crates on macOS, 5 on Windows and 3 on Linux. Almost all of them are system bindings, like objc2 on macOS and windows-sys on Windows. It builds from scratch in 11 seconds, and the binary is 1.3 MB. For comparison, here is the same counter on other frameworks (the number of crates on each system, a clean release build on M2 and the binary size):</p><pre>          macOS  Windows  Linux  Build   Binary<br>--------  -----  -------  -----  -----  -------<br>nimbo        14        5      3   11 s   1.3 MB<br>iced        152      159    237   59 s  10.9 MB<br>Tauri¹      217      223    265   64 s   9.9 MB<br>Xilem       157      177    257   65 s  12.2 MB<br>egui        177      178    279   74 s  14.3 MB<br>Slint       248      244    345   84 s  12.5 MB<br>GPUI        300      270    322   86 s   8.6 MB<br>GPUI Kit    411      395    518  144 s  19.4 MB</pre><p>¹ Plus the system WebView, which isn&#39;t part of the binary.</p><p>In the era of personal software and endless hacks, I want my own foundation for this kind of program, without depending on other people&#39;s frameworks. So I decided to finish nimbo properly. There&#39;s no first release yet because I&#39;m still working on the API, so I have no time to make cool videos for X. But if you need something minimal in Rust, you&#39;re welcome to try it.</p><p>The library is built in three layers. At the bottom is a common API for system stuff (windows, tray, context menu and so on), so the app code never has to touch it at all. Above it are headless components (behavior without styling), and any design can be built on top of them. On top is a base design in the style of system controls. The model for the library&#39;s API is SwiftUI.</p><h3>Week 4. Release: signing, packaging, updates</h3><p>The program is ready and tested, and all that&#39;s left is to ship a release. But that turned out to be not so simple either. There were three problems: signing, packaging and auto-update, and they took the last week.</p><h4>Signing</h4><p>In recent versions of macOS and Windows, unsigned apps just don&#39;t run. Windows is easier: SmartScreen shows a warning on the first launch, and once the user accepts it, the app starts. On macOS, though, the quarantine has to be removed from an unsigned app by hand with /usr/bin/xattr -dr com.apple.quarantine /Applications/Wavo.app, and a regular user is unlikely to do that.</p><p>I had to pay Apple $99 a year. And their payment form is straight from the early 2000s: I had to type in my card details by hand, and Apple charged the card on its own sometime later. In the end the charge failed on 3-D Secure. I had to temporarily lower the protection on my card and ask support to retry the payment, and the whole thing dragged on for several days. I can&#39;t remember the last time I saw something like that.</p><h4>Packaging</h4><p>A program for three systems needs installers for all three. On macOS the standard is a DMG. On Windows it&#39;s a setup.exe that installs the program, usually made with NSIS. On Linux it&#39;s an AppImage and a .deb package. Linux actually has more formats, but for now I picked these two.</p><p>At first it seemed easy to do with a Python script, so I gave that to the agent. There was one requirement: build and signing are separate. The build step downloads and compiles other people&#39;s code, so it must not have access to the signing keys. The second step only signs the finished files.</p><p>The script quickly grew to almost 2,000 lines. That surprised me, and I went looking for ready solutions, since after so many years someone must have solved this. I found a few (<a href="https://github.com/velopack/velopack">Velopack</a>, <a href="https://github.com/crabnebula-dev/cargo-packager">cargo-packager</a> and the Tauri bundler), but each has its own problems. Some can&#39;t separate build from signing. The worst part is that almost none of them can do everything on one machine (DMG and signing for macOS only on a Mac, deb and AppImage only on Linux, and Windows also needs NSIS). Velopack can build everything at once, but only on a Mac. In my opinion this is crazy. Packaging and signing should work on one computer, and ideally on any computer.</p><p>I looked through other people&#39;s repos, and from what I saw, only Mozilla does it properly. They package Firefox on Linux, even the DMG for macOS, but with wild hacks. For DMG they have their own fork of the C library <a href="https://github.com/mozilla/libdmg-hfsplus">libdmg-hfsplus</a>, which has no prebuilt releases, and their CI builds it straight from the repo at a specific commit. To use it myself, I would have to pull an artifact out of someone else&#39;s unversioned build, and I didn&#39;t want that. Well, I had an agent, so I gave this job to it too.</p><p>At first I wanted to make it part of nimbo. Then I realized it&#39;s a completely separate program and moved it to its own crate, <a href="https://github.com/vladkens/shipo">shipo</a>.</p><p>The main idea of shipo is that all installers can be built on any machine, even on Linux. Everything that exists on only one system (hdiutil on macOS, makensis for Windows, apt packages on Linux) is replaced with its own code. The other tools are downloaded at a pinned version and hash.</p><p>For macOS, shipo writes the DMG itself, together with the HFS+ file system per Apple&#39;s spec. It even includes the Unicode tables HFS+ uses to normalize file names. It also writes the .DS_Store that places the app icon and the /Applications shortcut in the window. It builds the .icns icon itself too, without sips and iconutil. Signing and notarization outside a Mac go through rcodesign and Apple&#39;s notarization service.</p><p>For Windows, the installer is custom too. It&#39;s a small prebuilt setup.exe in Rust with an empty marker inside. The packager replaces the icon, version and manifest in the app&#39;s exe and compresses the files into one archive. Then it appends the archive to the end of setup.exe and writes into the marker where that archive is. The uninstaller is the same setup.exe, just without the files.</p><p>For Linux, AppImage (a prebuilt runtime with a squashfs image of the app appended to it) and deb are built right in memory.</p><h4>Auto-update</h4><p>The third thing actually has nothing to do with packaging, but I had to do it too. On macOS many apps update with <a href="https://sparkle-project.org/">Sparkle</a>, but it works only on macOS. For Windows there&#39;s <a href="https://github.com/vslavik/winsparkle">WinSparkle</a>, which has a similar idea but is a different library. I wanted one thing for all systems, but didn&#39;t find anything here either. I decided that building and updating are close things and can live in one crate, so I made them together.</p><p>The idea of auto-update is simple. Each release also includes a small file that describes the latest version. The app reads it from time to time, and if the version is newer, it downloads and installs the update by itself.</p><p>In shipo it&#39;s one text file, update.txt, in the latest release on GitHub:</p><pre>version 1.2.0<br>notes https://github.com/me/hello/releases/tag/v1.2.0<br>macos-aarch64 394788 &lt;sha512&gt; https://github.com/me/hello/releases/download/v1.2.0/Hello-v1.2.0-macos-aarch64.dmg<br>windows-x86_64 285930 &lt;sha512&gt; https://github.com/me/hello/releases/download/v1.2.0/Hello-v1.2.0-windows-x64-setup.exe<br>linux-x86_64 412204 &lt;sha512&gt; https://github.com/me/hello/releases/download/v1.2.0/Hello-v1.2.0-linux-x86_64.AppImage<br>sig &lt;signature&gt;</pre><p>It has the version, a link to the release notes, and a line for each platform (size, SHA-512 hash and file URL). At the end is an Ed25519 signature of everything above. No separate update server is needed. The app just downloads the file from the latest GitHub release by a permanent link (releases/latest/download/update.txt).</p><p>The app checks the downloaded file by size and hash. It has two signing keys, a main one and a backup. If the main one leaks, the next release is signed with the backup.</p><p>The update uses the same installer as the first install. On macOS the library mounts the DMG, copies the app from it and replaces the old one. On Windows it runs setup.exe without a window. On Linux it replaces the AppImage file.</p><p>shipo has no separate HTTP library. Instead it has three short wrappers over the system ones (NSURLSession on macOS, WinHTTP on Windows, libcurl on Linux). So the updater has few dependencies: signature checking, errors and system bindings.</p><p>So in a week I got shipo, about 12,000 lines of code. Roughly 10,000 of them are the packager (with the setup.exe stub), and 2,400 are the library that goes into the app. Its packager builds installers for all three systems on one machine. The updater adds only 8–15 crates to the app depending on the system (Velopack and cargo-packager have over a hundred). In the end, releasing an app properly and setting up CI turned out to be harder than writing a UI renderer.</p><h3>Wrap up</h3><p>A program for a couple of days turned into a month of work. In that time there were about 850 commits and 167,000 changed lines (including prototypes and code I later threw away). Working with agents took about 90 active hours and 3.7 billion tokens, which is roughly $2,700 at API prices. The numbers are approximate because some agent logs got lost.</p><p>Most of the code was written by <a href="https://www.anthropic.com/claude/opus">Claude Opus 5.5</a>, and <a href="https://openai.com/index/gpt-6-astra/">GPT-6 Astra</a> did the reviews. Copilot on GitHub did about 390 more reviews until I hit its limit. Codex drew the graphics and images.</p><p>The work didn&#39;t end there. For anyone besides family and friends to hear about the program, I have to write about it on Reddit, X and other places, and that&#39;s a big separate job too. While doing it, I found a lot of similar programs. If I had seen them at the start, I probably wouldn&#39;t have built mine at all. But what&#39;s done is done. In the end I got my own cross-platform stack, and I hope to reuse it for other things.</p><p>All the programs from the post once more:</p><ul><li><a href="https://github.com/vladkens/wavo-app">Wavo</a>: local dictation for macOS, Windows and Linux;</li><li><a href="https://github.com/vladkens/wavo">wavo</a>: CLI and Rust crate for speech recognition in the style of ollama;</li><li><a href="https://github.com/vladkens/nimbo">nimbo</a>: native UI library with almost no dependencies;</li><li><a href="https://github.com/vladkens/shipo">shipo</a>: installers and auto-update for three systems from one machine.</li></ul><p>I wanted to make one small dictation app, and got an app and three libraries for it.</p><p>Before You Go…</p><ol><li>If you liked this article, <a href="https://medium.com/@vladkens/subscribe">subscribe</a> to get future updates.</li><li>Appreciate the content? Hold the clap button to give up to 50 claps!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3bfbe7dfda8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From iTerm To WezTerm]]></title>
            <link>https://medium.com/@vladkens/from-iterm-to-wezterm-24db2ccb8dc1?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/24db2ccb8dc1</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 04:50:14 GMT</pubDate>
            <atom:updated>2025-01-10T04:50:14.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tk3Ef_64dxXVD1mEIB6cqQ.png" /><figcaption>WezTerm</figcaption></figure><p>For many years, I used <a href="https://github.com/gnachman/iTerm2">iTerm2</a> as my main terminal emulator and probably spent hundreds of hours in it. Overall, I was satisfied with it, despite some strange recent updates like adding AI features, KeyChain integration, and <a href="https://news.ycombinator.com/item?id=42579472">security vulnerabilities</a>.</p><p>In recent years, new terminal emulators have appeared. I tried using them mainly for testing <a href="https://github.com/vladkens/macmon">macmon</a>. A couple of years ago, I tried switching to <a href="https://github.com/kovidgoyal/kitty">kitty</a>, which was faster due to GPU acceleration. However, it required too much customization and still looked very non-native for macOS. GPU acceleration was added to iTerm as well, so I stayed with it.</p><p>I also tried <a href="https://github.com/alacritty/alacritty">Alacritty</a>, but it is very basic and lacks the features I need. Recently, I tested <a href="https://github.com/ghostty-org/ghostty">Ghostty</a>, which has gained huge attention — it has nice defaults, but its RAM usage is concerning (around 250MB per empty tab). Currently, it also lacks <a href="https://github.com/ghostty-org/ghostty/issues/189">buffer search</a>, which makes the terminal useless for me.</p><p>I heard a lot of positive feedback about <a href="https://github.com/wez/wezterm">WezTerm</a> from <a href="https://github.com/bobuk">bobuk</a>. So I decided to try it out and use it for some time — and I am very satisfied with it.</p><p>The next part of the article will be about how to make WezTerm understandable for iTerm users to try it or switch completely.</p><h3>Initial</h3><p>WezTerm can be installed from Homebrew:</p><pre>brew install --cask wezterm</pre><p>When you first open WezTerm, it looks plain, non-native, and not very functional. But actually, it has everything you need. This is because WezTerm is cross-platform, unlike iTerm2, so the author left minimal default settings, leaving the rest of the configuration to the user. My goal is to achieve a similar experience in WezTerm as I had in iTerm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ki6IABDgDS9cvC3tFiHSA.png" /><figcaption>WezTerm on first launch</figcaption></figure><p>WezTerm does not have a graphical interface for configuration, and the setup is done through a Lua file (this is unusual for me, but Vim users are familiar with it). The configuration file can be located at ~/.wezterm.lua or ~/.config/wezterm/wezterm.lua. I prefer the second path because it is where <a href="https://github.com/fish-shell/fish-shell">Fish</a> and <a href="https://github.com/starship/starship">starship</a> store configs too.</p><p>Create a configuration file:</p><pre>mkdir -p ~/.config/wezterm/ &amp;&amp; touch ~/.config/wezterm/wezterm.lua</pre><p>And then add the boilerplate code for configuration:</p><pre>local wezterm = require &quot;wezterm&quot;<br>local config = wezterm.config_builder()<br>local action = wezterm.action<br> <br>-- (here will be added actual configuration)<br> <br>return config</pre><h3>Appearance</h3><p>First, I want to change the default font, its size, and disable ligatures (because it’s important to see the actual characters in case of some logs).</p><pre>config.font = wezterm.font {<br>  family = &#39;JetBrains Mono&#39;,<br>  weight = &#39;Medium&#39;,<br>  harfbuzz_features = { &#39;calt=0&#39;, &#39;clig=0&#39;, &#39;liga=0&#39; }, -- disable ligatures<br>}<br>config.font_size = 14.0<br>config.line_height = 1.0</pre><p>Save the file, and the changes should be applied immediately (yes, no reload required!).</p><p>Next, I want to change the theme and set it to follow the current system theme automatically. For the past year, I have been using <a href="https://github.com/catppuccin/catppuccin">Catppuccin</a> themes, and I am very happy with them. They rarely have issues where some text colors blend with the background. To make the theme switch automatically based on the current system theme, we need to write a small Lua function (I copied it from the documentation):</p><pre>local function schemeforappearance(appearance)<br>  if appearance:find &quot;Dark&quot; then<br>    return &quot;Catppuccin Macchiato&quot;<br>  else<br>    return &quot;Catppuccin Latte&quot;<br>  end<br>end<br> <br>config.colorscheme = scheme_for_appearance(wezterm.gui.getappearance())</pre><p>I forgot to mention that the Catppuccin theme, like many other popular themes, is pre-installed in WezTerm, so you don’t need to install it separately like in iTerm, which is very cool. Of course, you can also set up <a href="https://wezfurlong.org/wezterm/config/appearance.html#defining-your-own-colors">your own colors</a>.</p><p>The default padding also seems a bit large, so let’s make it smaller. I also had a Blinking Line Cursor (I don’t remember if this is the default or not in iTerm). Let’s set both configurations:</p><pre>config.window_padding = { left = &#39;0.5cell&#39;, right = &#39;0.5cell&#39;, top = &#39;0.5cell&#39;, bottom = &#39;0.5cell&#39; }<br>config.defaultcursorstyle = &#39;BlinkingBar&#39;</pre><h3>Window style</h3><p>In iTerm, I used the Minimal theme to save vertical space for tabs. We can do the same in WezTerm (the default tabs don’t look very good). Also possible to add some transparency and blur to the window. I didn’t use this in iTerm, but let’s try it now:</p><pre>config.windowdecorations = &#39;RESIZE|INTEGRATEDBUTTONS&#39;<br>config.windowbackgroundopacity = 0.96<br>config.macoswindow_backgroundblur = 20</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRc2hmHTelo9bYj4fPbWOw.png" /><figcaption>WezTerm tabs decoration</figcaption></figure><h3>Maximize on start-up</h3><p>In iTerm, I usually set large values for Cols/Rows to make the start window bigger. This approach is a bit outdated, so let’s make the window open in full screen when the terminal starts.</p><pre>-- https://github.com/wez/wezterm/issues/3299#issuecomment-2145712082<br>wezterm.on(&quot;gui-startup&quot;, function(cmd)<br>  local active = wezterm.gui.screens().active<br>    local tab, pane, window = wezterm.mux.spawn_window(cmd or {})<br>  window:guiwindow():setposition(active.x, active.y)<br>  window:guiwindow():set_innersize(active.width, active.height)<br>end)</pre><h3>Key bindings</h3><p>Finally, the most important part is setting up hotkeys — it’s hard to give up what you’ve been used to for years. An important thing for me is Split Panels with Cmd + D / Cmd + Shift + D. Cmd + W should close the current active panel, not the whole tab. Cmd + K – clear the current screen. Cmd + ← / Cmd + → for start/end of the line. I think these are all defaults from iTerm, so let&#39;s make them the same in WezTerm:</p><pre>config.keys = {<br>  { key = &#39;d&#39;, mods = &#39;CMD|SHIFT&#39;, action = action.SplitVertical { domain = &#39;CurrentPaneDomain&#39; } },<br>  { key = &#39;d&#39;, mods = &#39;CMD&#39;, action = action.SplitHorizontal { domain = &#39;CurrentPaneDomain&#39; } },<br>  { key = &#39;k&#39;, mods = &#39;CMD&#39;, action = action.ClearScrollback &#39;ScrollbackAndViewport&#39; },<br>  { key = &#39;w&#39;, mods = &#39;CMD&#39;, action = action.CloseCurrentPane { confirm = false } },<br>  { key = &#39;w&#39;, mods = &#39;CMD|SHIFT&#39;, action = action.CloseCurrentTab { confirm = false } },<br>  { key = &#39;LeftArrow&#39;, mods = &#39;CMD&#39;, action = action.SendKey { key = &#39;Home&#39; } },<br>  { key = &#39;RightArrow&#39;, mods = &#39;CMD&#39;, action = action.SendKey { key = &#39;End&#39; } },<br>  { key = &#39;p&#39;, mods = &#39;CMD|SHIFT&#39;, action = action.ActivateCommandPalette },<br>}</pre><p>WezTerm also has a Command Execution menu. I haven’t used it much yet, but just in case, I bind it to the same keys as in VSCode / Zed — Cmd + Shift + P.</p><p><em>Note: In the configuration, the </em><em>key value is case-sensitive, so </em><em>{ key = &#39;d&#39;, ... } and </em><em>{ key = &#39;D&#39;, ... } are different things (basically </em><em>key=&#39;D&#39; is the same as </em><em>key=&#39;d&#39;, mods=&#39;SHIFT&#39;). I initially got confused with this.</em></p><h3>Fin</h3><p>Overall, I am very satisfied with WezTerm and have fully switched to using it daily. One cool feature I want to mention is the quick connect to servers in Known hosts via SSH (Command Palette → type server name → Enter OR Nav Bar → Shell → Click on server name). WezTerm also has <a href="https://wezfurlong.org/wezterm/recipes/workspaces.html">Workspaces</a> — an alternative to tmux, but I haven’t used it actively yet.</p><p>Here a <a href="https://gist.github.com/vladkens/f2ae7c374c1752c4b1581c5e7dffa900">gist</a> with the final config from this article.</p><ol><li><a href="https://wezfurlong.org/wezterm/config/files.html">https://wezfurlong.org/wezterm/config/files.html</a></li><li><a href="https://alexplescan.com/posts/2024/08/10/wezterm/">https://alexplescan.com/posts/2024/08/10/wezterm/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24db2ccb8dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2024 In Review]]></title>
            <link>https://medium.com/@vladkens/2024-in-review-d4a0332c925d?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4a0332c925d</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[personal]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 01:06:33 GMT</pubDate>
            <atom:updated>2025-01-02T01:06:33.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3geGj6kprNwvif1dDTXpyA.png" /><figcaption>Image generated with Dall-E</figcaption></figure><p>I have never written an annual report on my work before, but since I also spend time on open source projects, I decided to write one (maybe it will become a tradition).</p><h3>Programming Languages and Tools</h3><h3>Rust</h3><p>The main change in my work was the active use of Rust in the second half of the past year. I mainly write in Rust where I used to write in Go. Overall, the language is more complex than Go and sometimes confusing with the borrow checker, but in general, it is quite convenient to write — I can’t say that the speed of writing code significantly decreases compared to other languages — in general, the approaches that need to be used are roughly the same for all languages.</p><p>What I like about Rust:</p><ul><li>crates ecosystem — many libraries available and can be installed in one command</li><li>single binary file and low memory consumption</li><li>ability to write applications of various directions (web-app, tui, gui, parsers, etc.)</li></ul><p>What I don’t like about Rust:</p><ul><li>slow Docker image builds (<a href="https://vnotes.pages.dev/fast-multi-arch-docker-for-rust">my solution</a>)</li><li>a large number of sub-dependencies for web projects (any project on axum will contain 200+ dependencies)</li><li>use of C-binding in “core” libraries like rust-tls (ring) — complicates cross-compilation because you have to maintain a C toolchain as well (fixed through Zig build, but it looks monstrous)</li><li>lack of finished solutions for serde (<a href="https://github.com/serde-rs/serde/issues/2254">default values</a>, <a href="https://users.rust-lang.org/t/serde-how-to-parse-json-partially-7-years-later/97030">partial initialization</a>)</li></ul><p>It’s nice to write various parsers in Rust, and then they can be coolly parallelized (with <a href="https://docs.rs/rayon/latest/rayon/">rayon</a> or <a href="https://docs.rs/tokio/latest/tokio/fs/index.html">tokio</a>), in Go I had a problems with this due to immutable strings and lack of GC control.</p><h3>Main languages</h3><p>The main languages remained the same: Python, NodeJS/TypeScript. I also actively used NextJS on several projects, overall I was satisfied — it’s faster and easier to write frontends, but it’s quite difficult to find problem’s solutions sometimes (many Github issues, often they are open, and the comments contain answers that no longer work).</p><p>The main fail of the year in the NodeJS ecosystem is the update of ESLint from 8 -&gt; 9 — completely incompatible API with all existing plugins, the configuration file became larger and more complex — it’s not clear why the authors made this diversion. I also tried <a href="https://biomejs.dev/">Binome</a> as an alternative to ESLint / Prettier, but it’s completely different and you need to redo a lot, and not everything you need is available at the moment, I continue to monitor this project.</p><p>I also tried Zig, but didn’t write anything serious. Personally, I didn’t understand why this language is needed. At the time I tried it, there was no even package manager yet. Obviously Zig is a competitor to C (not Rust), but C is now much richer in its toolkit and support in other languages. The only thing I can point out is zig build which can build C projects too and does it with less problems.</p><h3>About LLM</h3><p>I want to separately note about use of GPTs in work. I have an opportunity to do business tasks in the format of parsing and analyzing texts. What a couple of years ago was done with a bunch of regex, etc., can now be done through GPT and it works great! I tried using local Llama2, but it would have taken weeks to process my data on M2 chip. I redo the solution to use ChatGPT API and processed the data in a couple of days. It’s good that all LLMs support openai-client API in Python, so the code almost didn’t need to be rewritten. Among the disadvantages of LLama-like aka local running, I also want to note the lack of support for <a href="https://platform.openai.com/docs/guides/function-calling">Function calling</a> (to guarantee to bring the LLM response to the desired structure, in my case). The last time I did something serious was more than six months ago, maybe a lot has changed. I also tested gemma2, the inference speed was impressive, and the quality of the answers was not much worse.</p><p>As local runners, I used <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> and <a href="https://ritviknag.com/markdown-to-medium/mlx_ml">https://github.com/ml-explore/mlx</a> — the second one uses Mac resources better (checked through <a href="https://github.com/vladkens/macmon">macmon</a>), but new models come out a bit slower on it. Some people use <a href="https://github.com/ollama/ollama">ollama</a>, but I didn’t understand why, considering that it has an incompatible client with openai-client API and slower performance.</p><h3>Blog</h3><p>Initially, I ran my blog only on Medium, but it’s not comfortable to write text there — it’s much easier to write and edit in the same editor where I write code (plus my editor has Copilot). Therefore, I decided to move my blog to a static page generator. As an engine, I chose <a href="https://www.getzola.org/">Zola</a> (Rust-based, simple, and fast); I also tried <a href="https://astro.build/">Astro</a>, but it’s too big and complex for such a simple task. Overall, Zola is good, but it lacks some filters in <a href="https://keats.github.io/tera/docs/">templating</a>, not enough flexibility in file structure, and not all popular languages are supported in code highlighting.</p><p>I left Medium as a fallback for old readers. I also made a cross-post on <a href="https://dev.to/vladkens">dev.to</a>, but there are very few views. Medium is disappointed with the lack of the ability to automate cross-posting (they have a deprecated API, but it does not support updating articles and code highlights). Most likely, it’s possible to reverse engineer how they save articles through their editor (changes are sent as diffs). Does anyone else need this besides me?</p><h3>New projects</h3><p>Last year I launched several new projects (in chronological order):</p><ul><li><a href="https://github.com/vladkens/timewiz">timewiz.cc</a> (react, webapp) – a tool to find common working hours for distributed teams (an alternative to worldtimebuddy.com, I don&#39;t remember exactly why I made my own version). Score: fail.</li><li><a href="https://github.com/vladkens/ecloop">ecloop</a> (c, cli) – secp256k1 elliptic curve implementation for Apple chips. Mainly an educational project to understand cryptography, SIMD optimizations, etc. Added several standard use cases for finding Bitcoin keys by brute force, but mathematically this is pointless, so as I said earlier, this is more of an interesting educational project (and I wanted to publish a series of articles on cryptography, but didn&#39;t have time last year, I hope to do it this year). Some people use this project in hopes of finding something. I also had ideas to add Metal API support – but that takes a lot of time, so I switched to other projects. Score: okay.</li><li><a href="https://github.com/vladkens/macmon">macmon</a> (rust, tui) – TUI program for monitoring MacOS performance (CPU/GPU/ANE usage, RAM, temps). My first public Rust project, a lot of reverse engineering of how <a href="https://vnotes.pages.dev/powermetrics-macos">powermetrics in MacOS</a> works, C-bindings. The project is used both by users in TUI mode and by other projects in headless mode (JSON metrics). Score: success.</li><li><a href="https://github.com/vladkens/ghstats">ghstats</a> (rust, axum, htmx, webapp) – a small self-hosted service that collects and saves GitHub repo statistics, has several built-in views and an API to retrieve all statistics. The project started well, but then kind of fizzled out in terms of issues and feature requests, most likely users are satisfied with the current functionality. I would like to add more visualizations, but I haven&#39;t had time for that yet. The main thing for now is that the statistics are collected and saved, so something can be done with this in the future. Technically, I like that the service consumes only 10 MB of RAM. Score: okay.</li><li><a href="https://github.com/vladkens/ogp">ogp</a> (rust, axum, api-service) – a small project for generating <a href="https://vnotes.pages.dev/og-image-generator">OGP articles preview</a> as a service. Used in this blog (you can check by sending this article to your friends in a messenger or social network 😀). Worked with the SVG standard (I thought it was more adequate) and generating PNG from SVG. Score: more of fail.</li><li><a href="https://github.com/vladkens/compose-updater">compose-updater</a> (python, api-service) – a project for updating the version of a docker image from CI in a closed infrastructure. I didn&#39;t find anything ready to solve this task. There is <a href="https://github.com/containrrr/watchtower">watchtower</a>, but it&#39;s more about keeping up-to-date docker images, rather than updating a specific one, and also I couldn&#39;t run it with ECR repos – the author made a super minimalist image in which I couldn&#39;t enter through sh to debug. The second alternative is <a href="https://github.com/umputun/updater">umputun/updater</a>, but it&#39;s more about running different shell commands through a webhook. I chose Python because I didn&#39;t find a Rust crate for Docker API (most likely it exists, I just didn&#39;t understand which one is really good). Score: – (I didn&#39;t promote the project anywhere, I use it for my own purposes for now).</li></ul><h3>Existing projects</h3><ul><li><a href="https://github.com/vladkens/twscrape">twscrape</a> (python, lib) – a library <a href="https://vnotes.pages.dev/twscrape">for parsing</a> data from X/Twitter. Mainly the project is in maintenance mode, I check its functionality every few months, and there have been no requests for new features.</li><li><a href="https://github.com/vladkens/apigen-ts">apigen-ts</a> (typescript, lib) – a library <a href="https://vnotes.pages.dev/simple-typescript-api-client-generator">for generating</a> TypeScript client OpenAPI spec. I continue to use it in my projects; I also see that there are a small number of other users. My relevance has slightly decreased due to the NextJS/TRPC stack, but in other configurations (e.g. FastApi + React), it is still relevant, so use it. Periodically there are requests to fix something or add a feature.</li></ul><h3>Abandoned projects</h3><p>I also have several projects that I didn’t finish and abandoned. I’ll write about them here, maybe someone needs something from this, then I can return to on it.</p><ul><li>anypost – cross-posting between static blog, Medium, Dev.to, Substack, and collecting joined article statistics. I abandoned the project due to the lack of an API at Medium – the only solution I found was through protocol reverse and session cookie.</li><li>bcloop – a program to walk Bitcoin-like blockchain and compile the final UTXO list. I abandoned it because I couldn&#39;t figure out how to effectively create a HashMap-like structure with external memory support to run on computers with small RAM (less than 32GB, LOL).</li><li>tg-watcher – a program that listens to all incoming messages in Telegram (chats &amp; channels) and saves their history in a separate database with the ability to search through these messages later. I have the first version that just saves messages in json files, but I didn&#39;t develop the idea further.</li></ul><h3>Devices</h3><p>I’m not a big tech geek, but I want to say about a few devices which made my life easier:</p><ul><li><a href="https://store.mele.cn/products/mele-quieter-4c-n100-3-4ghz-fanless-mini-computer-lpddr4x-win11-hdmi-4k-wi-fi-5-bt-5-1-usb-3-2-2-usb-2-0-1-type-c-1?variant=43958369648818">MeLE Fanless Quieter 4C</a> — a small fanless PC for <em>homelab</em>, I use it as a native Linux via SSH for testing various programs and keep some cron jobs on it for data collection. It’s cool that it’s silent because it has no fan, but it heats up a lot under load. The performance of the N100 chip surprised me — only 2x slower than M2 chip (tested with ecloop bench, single core).</li><li><a href="https://promate.net/products/hdmi-pd100">Promate HDMI-PD100</a> — nice cable format to connect a monitor and my Mac. One cable is needed to charge and transmit the video stream. Before that, I used hubs, but it’s a big block. I’m glad I see fewer wires.</li></ul><h3>At Glance</h3><p>Over the year, 8 articles were written, totaling 5203 views. Top-3 articles:</p><ul><li><a href="https://vnotes.pages.dev/htmx-table-sorting">Table sorting and pagination with HTMX</a> — 1714</li><li><a href="https://vnotes.pages.dev/macmon">macmon — Mac Usage Monitor in Terminal</a> — 953</li><li><a href="https://vnotes.pages.dev/aws-wireguard-vpn-terraform">Setting up WireGuard VPN at AWS with Terraform</a> — 642</li></ul><p><em>Data aggregated from this site (with </em><a href="https://umami.is/"><em>umami</em></a><em>), Medium, and Dev.to. </em><a href="https://github.com/vladkens/blog/blob/main/%3Cem%3Estats_at%3C/em%3Eglance.py"><em>Script</em></a><em>.</em></p><p>Public GitHub projects — totaling 312 commits, 49 issues closed, 43 releases created, and 1394 stars gained. Top-3 repos:</p><ul><li><a href="https://github.com/vladkens/twscrape">twscrape</a> — +802 stars / +52515 views</li><li><a href="https://github.com/vladkens/macmon">macmon</a> — +420 stars / +6899 views</li><li><a href="https://github.com/vladkens/ghstats">ghstats</a> — +128 stars / +2757 views</li></ul><p><em>Data aggregated with </em><em>ghstats.</em></p><p>I hope I will see a different top with new projects this year 😀</p><h3>Donations</h3><p>In twscrape repository I was asked to make it possible to send coffee as donations. Over the year I received 38 cups of coffee from 10 people. I spend these coffees on an annual <a href="https://www.parallels.com/">Parallels</a> subscription, which allows me to test some apps on Windows. Also, I partially paid from this fund for MeLE and VPS, which I used to test apps as well. Many thanks for supporting my work!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4a0332c925d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy FastAPI application with SQLite on Fly.io]]></title>
            <link>https://medium.com/@vladkens/deploy-fastapi-application-with-sqlite-on-fly-io-5ed1185fece1?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed1185fece1</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 01:32:37 GMT</pubDate>
            <atom:updated>2024-10-22T01:32:37.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPwmnH5wxVIHNcZWwKtItQ.png" /></figure><p>Cloud solutions are good for medium and large projects, but too heavy for small personal projects. If you want to launch something small (a few api endpoins and a small repository), there are three options:</p><ul><li>Use the same approaches as for “big” projects (AWS ECS/EKS, RDS), but they are redundant, and infrastructure code can be larger than code of the actual project. Also it’s expensive (~$100).</li><li>Use serverless solutions (Lambda, Vercel). Most cloud providers have such solutions, but these services have difficulties with simple databases — they provide cheap vendor solutions (AWS) or require a managed database, which again is expensive (mostly nothing for serverless, ~$20 for DB)</li><li>Use VPS with Docker. It is cheap (~$5 for small machine) and almost no need to manage infrastructure, but deployments sucks (needs private or self-hosted regestry, SSH access from CI).</li></ul><p>I usually write my small applications using SQLite, it’s a handy little single file database that works in any programming language and can be copied to local machine to analyze data for example. So I was looking for some middleware solution that combines the serveless approach, ease of deployment and ability to use SQLite and found Fly.io.</p><h3>Setup</h3><p>If you don’t have an account in Fly.io — you need to <a href="https://fly.io/app/sign-up">create</a> it. Also <a href="https://fly.io/docs/flyctl/install/">CLI tool</a> called flyctl required to manage projects. Fly.io can be deployed both locally and from CI.</p><p>flyctl makes deploy from project&#39;s root folder from Dockerfile, which is cool, because same Dockerfile can be used in other systems. For play with Fly.io, I prepared a simple FastAPI project that stores state in database – generic url shortener with click counting.</p><p>Dockerfile:</p><pre>FROM python:3.13-alpine<br>WORKDIR /app<br> <br>COPY ./requirements.txt .<br>RUN pip install --no-cache-dir --upgrade -r requirements.txt<br> <br>COPY . /app<br> <br>ENV HOST=0.0.0.0 PORT=8080<br>EXPOSE ${PORT}<br>CMD uvicorn main:app --host ${HOST} --port ${PORT}</pre><p>main.py:</p><pre>import asyncio<br>import random<br>import string<br>from urllib.parse import urlparse<br> <br>import aiosqlite<br>from fastapi import FastAPI, HTTPException, Request<br>from fastapi.responses import RedirectResponse<br> <br>DB_PATH = &quot;/data/app.db&quot;<br> <br>app = FastAPI()<br> <br>async def get_db() -&gt; aiosqlite.Connection:<br>    if db := getattr(getdb, &quot;db&quot;, None):<br>        if db.is_alive:<br>            return db<br> <br>    db = await aiosqlite.connect(DBPATH, loop=asyncio.get_eventloop())<br>    db.row_factory = aiosqlite.Row<br> <br>    qs = &quot;&quot;&quot;<br>    CREATE TABLE IF NOT EXISTS links (<br>        created_at INTEGER DEFAULT (strftime(&#39;%s&#39;, &#39;now&#39;)),<br>        short_code TEXT PRIMARY KEY,<br>        full_url TEXT NOT NULL,<br>        clicks INTEGER DEFAULT 0<br>    )<br>    &quot;&quot;&quot;<br> <br>    await db.execute(qs)<br>    await db.commit()<br> <br>    setattr(getdb, &quot;db&quot;, db)<br>    return db<br> <br>def random_code(length=8) -&gt; str:<br>    alphabet = string.ascii_letters + string.digits<br>    return &quot;&quot;.join(random.choice(alphabet) for x in range(length))<br> <br>def isvalidurl(/service/url: str) -&gt; bool:<br>    try:<br>        parts = urlparse(url)<br>        return all([parts.scheme, parts.netloc])<br>    except ValueError:<br>        return False<br> <br>@app.post(&quot;/&quot;)<br>async def shorten(url: str, req: Request):<br>    if not isvalid/service/https://medium.com/url(url):<br>        raise HTTPException(status_code=400, detail=&quot;Invalid URL&quot;)<br> <br>    host = req.headers.get(&quot;host&quot;)<br>    if host is None:<br>        raise HTTPException(status_code=500, detail=&quot;Missing host header&quot;)<br> <br>    shortcode = randomcode()<br>    db = await get_db()<br>    qs = &quot;INSERT INTO links (shortcode, fullurl) VALUES (?, ?)&quot;<br>    await db.execute(qs, (short_code, url))<br>    await db.commit()<br> <br>    return f&quot;https://{host}/{short_code}&quot;<br> <br>@app.get(&quot;/&quot;)<br>async def list_links():<br>    db = await get_db()<br>    qs = &quot;SELECT shortcode, full_url, clicks FROM links ORDER BY createdat DESC&quot;<br>    async with db.execute(qs) as cursor:<br>        return await cursor.fetchall()<br> <br>@app.get(&quot;/{short_code}&quot;)<br>async def redirect(short_code: str):<br>    db = await get_db()<br>    qs = &quot;&quot;&quot;<br>    UPDATE links SET clicks = clicks + 1 WHERE short_code = ?<br>    RETURNING full_url<br>    &quot;&quot;&quot;<br> <br>    async with db.execute(qs, (short_code,)) as cursor:<br>        if row := await cursor.fetchone():<br>            return RedirectResponse(row[&quot;full_url&quot;])<br> <br>    raise HTTPException(status_code=404)</pre><p>requirements.txt:</p><pre>aiosqlite<br>fastapi<br>uvicorn</pre><h3>Deploy</h3><p>To deploy our code, first we need to create a Fly.io project. This can be done either in the web interface or with flyctl. To create proejct with CLU tool in root folder (where code located) flyctl launch should be runned. This command will offer to select desired hardware and will create fly.toml file:</p><pre>fly launch --build-only</pre><p>You can modify project in future by changing parameters in this file or via web ui. The basic fly.toml looks fine, but SQLite requires Storage, which can be created with:</p><pre>fly volumes create sqlite_data -s 1 -r ams</pre><p>where -s 1 sets volume size to 1 GB (default is 3 GB), and -r is region in which volume will be created (use same region in which Fly.io project is created). You can always change storage size later.</p><p>The last thing to do is to add a mounts section to fly.toml, which attaches the volume to the application:</p><pre>[mounts]<br>source = &quot;sqlite_data&quot;<br>destination = &quot;/data&quot;</pre><p>sqlite<em>data is the name of the storage, </em><em>/data is the path where volume will be connected. This is essentially same as </em><em>docker run --mount source=sqlite</em>data,target=/data or corresponding Docker Compose section.</p><p>SQLite cannot be writable from more than one app, and Fly.io by default creates 2 instances for an app, so we can specify the number of replicas as one just in case:</p><pre>fly scale count 1</pre><p>All configurations are done now and we can deploy our app with command:</p><pre>fly deploy</pre><p>The app should boot successfully and the public DNS name will be printed to console. Now we can check it out by posting some url to shortener:</p><pre>❯ curl -X POST &#39;https://fly-fastapi-sqlite.fly.dev/?url=https://example.com&#39;<br>https://fly-fastapi-sqlite.fly.dev/8ydmfAcK</pre><p>Then we can visit this link, it should redirect to https://example.com. Finally, we can check that clicks are updated:</p><pre>❯ curl -s &#39;https://fly-fastapi-sqlite.fly.dev/&#39; | jq<br>[<br>  {<br>    &quot;short_code&quot;: &quot;8ydmfAcK&quot;,<br>    &quot;full_url&quot;: &quot;https://example.com&quot;,<br>    &quot;clicks&quot;: 1<br>  }<br>]</pre><p>To check that database state saved between deployments, we can perform new deployment with fly deploy and check that links list remained same as above (1 link, 1 click).</p><h3>Migrations</h3><p>If you are using an external solution for migrations, rather than running them from code when app starts, then only way to run migration is to put it in Dockerfile as part of the RUN command.</p><h3>Backup</h3><p>We can connect to machine with fly ssh console and then in /data folder interact with database file. Also we can copy database file to local machine with:</p><pre>fly ssh sftp get /data/app.db ./app-backup.db</pre><h3>Conclusion</h3><p>Fly.io is a simple and convenient service for deploying applications. Deploy works from Docker Containers, additional services include PSQL, Redis, S3 like storage (unlike Vercel). It’s cheap, the cheapest service costs 3 dollars (1 shared CPU / 256 MB) — maybe even less, if you have little traffic — container shuts down after a few minutes without activity and automatically turns on when traffic appears.</p><p>On downside, there is no built-in solution for scheduled tasks — instead, the official solution is to set up a separate server with crontab and run tasks from it – it&#39;s kind of creepy.</p><p><strong>Before You Go…</strong></p><ol><li>If you liked this article, <a href="https://medium.com/@vladkens/subscribe">subscribe</a> to get future updates.</li><li>Appreciate the content? Hold the clap button to give up to 50 claps!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed1185fece1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up WireGuard VPN at AWS with Terraform]]></title>
            <link>https://medium.com/@vladkens/setting-up-wireguard-vpn-at-aws-with-terraform-f3054cba21fa?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3054cba21fa</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 22:31:25 GMT</pubDate>
            <atom:updated>2024-10-12T22:33:53.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoIxKOFDo01eW3xCGXEyNQ.png" /></figure><p>All resources in AWS work inside private VPC. Sometimes you may need to access these resources from local computer (e.g. to interact with database). Some resources, like RDS, have the option to enable public access to them — but this is unsecure. Of course you can configure Security Group to allow access to public resource only from allowed IPs to make this setup a bit better, but still in this case all your colleagues must to have static IPs, which is not always true.</p><h3>Objective</h3><p>We need to provide a quick and easy solution to give access to internal AWS VPC resources for our team. In general, there are two ways to do this:</p><ol><li>Bastion / Jump Host — EC2 instance with SSH access for each member</li><li>Private VPN — EC2 instance with VPN config for each member</li></ol><p>In both cases we need to to setup a custom EC2 instance, so second variant seems more convenient to me.</p><h3>Preparation</h3><p>In addition to the traditional Terraform client, we will need WireGuard CLI tools to generate a key pair. You can install WireGuard tools on macOS via brew:</p><pre>brew install wireguard-tools</pre><h3>Initial Terraform</h3><p>First, as usual, we need to configure Terraform Provider and get VPC and Public Subnet data where we want to host our VPN server. On this step you can export VPC / Public Subnet from another layer or pass them via variables. I will access my VPC and Public Subnet by name.</p><pre>terraform {<br>  required_providers {<br>    aws = { source = &quot;hashicorp/aws&quot;, version = &quot;~&gt; 5.70&quot; }<br>  }<br>}<br> <br>provider &quot;aws&quot; {<br>  profile = &quot;default&quot;   # Change this to your AWS profile<br>  region  = &quot;us-east-1&quot; # Change this to your AWS region<br>}<br> <br># MARK: Getting VPC and Subnets<br> <br>locals {<br>  vpcname = &quot;myvpc&quot; # Change this to yor VPC name<br>}<br> <br>data &quot;aws_vpc&quot; &quot;vpc&quot; {<br>  filter {<br>    name   = &quot;tag:Name&quot;<br>    values = [local.vpc_name]<br>  }<br>}<br> <br>data &quot;aws_subnets&quot; &quot;public&quot; {<br>  filter {<br>    name   = &quot;vpc-id&quot;<br>    values = [data.aws_vpc.vpc.id]<br>  }<br> <br>  tags = { Tier = &quot;Public&quot; } # This is custom tag<br>}</pre><h3>WireGuard Server</h3><p>To setup WireGuard server we need to know AMI ID of OS will be running on EC2 instance, prepare key pairs for the server and for client (peers), create a security group to control network access, create and assing Elastic IP to be sure that the server IP will be same.</p><h3>Generate key pairs</h3><p>First we need to create key pairs which can be generated with this command:</p><pre>bash -c &#39;priv=$(wg genkey); pub=$(echo $priv | wg pubkey); printf &quot;$priv\n$pub\n&quot;&#39;</pre><p>In output first line is privkey, second is pubkey.</p><p>I will generate it twice, one for server, second for first client (peer). Then for each new peer you will need to generate new key pairs. I will same generated keys to secrets.yaml file, but you can use different ways to store secrets.</p><p>Generate secrets for server and first peer (do not use this keys in your setup):</p><pre>❯ bash -c &#39;priv=$(wg genkey); pub=$(echo $priv | wg pubkey); printf &quot;$priv\n$pub\n&quot;&#39;<br>0McsAe5Y/oupwJeju+94ZFl1bmp2KIX2bBQGk0cSWXQ=<br>KeV+BlZMfCgRhdfaHqpdPp23Nu/otir+6VR02DER7lU=<br> <br>❯ bash -c &#39;priv=$(wg genkey); pub=$(echo $priv | wg pubkey); printf &quot;$priv\n$pub\n&quot;&#39;<br>SK71fHXpTo2cGKvlLLTlu+0AqpwaNWG30rzGXFIryk0=<br>wf3j1JLhXw/u6iDZf9Qhq0lU34exF8mrHdGzz/u+xFU=</pre><p>Then save generated keys to secrets.yaml</p><pre>wg_server:<br>  privkey: 0McsAe5Y/oupwJeju+94ZFl1bmp2KIX2bBQGk0cSWXQ=<br>  pubkey: KeV+BlZMfCgRhdfaHqpdPp23Nu/otir+6VR02DER7lU=<br> <br>wg_peers:<br>  - name: user1<br>    addr: 172.16.16.1<br>    privkey: SK71fHXpTo2cGKvlLLTlu+0AqpwaNWG30rzGXFIryk0=<br>    pubkey: wf3j1JLhXw/u6iDZf9Qhq0lU34exF8mrHdGzz/u+xFU=</pre><h3>Setup script</h3><p>Then we need create WireGuard setup script which will be runned during EC2 creation. User data will be generated from this script and populated from secrets.yaml file. So create templates directory with two files in it: wg-init.tpl (general setup script) and wg-peer.tpl (peer info).</p><pre>#!/bin/bash<br>sudo apt update &amp;&amp; apt -y install net-tools wireguard<br> <br># https://github.com/vainkop/terraform-aws-wireguard/blob/master/templates/user-data.txt<br>sudo mkdir -p /etc/wireguard<br>sudo cat &gt; /etc/wireguard/wg0.conf &lt;&lt;- EOF<br>[Interface]<br>PrivateKey = ${wg_privkey}<br>ListenPort = ${wg_port}<br>Address = ${wg_cidr}<br>PostUp = sysctl -w -q net.ipv4.ip_forward=1<br>PostUp = iptables -A FORWARD -i %i -j ACCEPT; iptables -A FORWARD -o %i -j ACCEPT; iptables -t nat -A POSTROUTING -o ENI -j MASQUERADE<br>PostDown = sysctl -w -q net.ipv4.ip_forward=0<br>PostDown = iptables -D FORWARD -i %i -j ACCEPT; iptables -D FORWARD -o %i -j ACCEPT; iptables -t nat -D POSTROUTING -o ENI -j MASQUERADE<br> <br>${wg_peers}<br>EOF<br> <br># Make sure we replace the &quot;ENI&quot; placeholder with the actual network interface name<br>export ENI=$(ip route get 8.8.8.8 | grep 8.8.8.8 | awk &#39;{print $5}&#39;)<br>sudo sed -i &quot;s/ENI/$ENI/g&quot; /etc/wireguard/wg0.conf<br> <br>sudo wg-quick up wg0<br>sudo systemctl enable wg-quick@wg0</pre><pre>[Peer]<br># ${peer_name}<br>PublicKey = ${peer_pubkey}<br>AllowedIPs = ${peer_addr}</pre><p>Next we need to prepare user data script in terraform file from this templates.</p><pre># MARK: Config<br> <br>locals {<br>  wg_cidr = &quot;172.16.16.0/20&quot; # CIDR of WireGuard Server<br>  wg_port = 51820            # Port of WireGuard Server<br>  secrets = yamldecode(file(&quot;secrets.yaml&quot;))<br> <br>  userdata = templatefile(&quot;templates/wg-init.tpl&quot;, {<br>    wgcidr    = local.wgcidr<br>    wgport    = local.wgport<br>    wgprivkey = local.secrets.wgserver.privkey<br>    wg_peers = join(&quot;\n&quot;, [<br>      for p in local.secrets.wg_peers :<br>      templatefile(&quot;templates/wg-peer.tpl&quot;, {<br>        peer_name   = p.name<br>        peer_pubkey = p.pubkey<br>        peer_addr   = p.addr<br>      })<br>    ])<br>  })<br>}</pre><h3>Server setup</h3><p>Then we need to select Ubuntu AMI, create Security Group and Elastic IP.</p><pre># MARK: Server dependencies<br> <br>data &quot;aws_ami&quot; &quot;ubuntu&quot; {<br>  owners      = [&quot;099720109477&quot;] # Canonical<br>  most_recent = true<br>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-arm64-server-*&quot;]<br>  }<br>}<br> <br>resource &quot;aws_eip&quot; &quot;wireguard&quot; {<br>  tags = { Name = &quot;wireguard&quot; }<br>}<br> <br>resource &quot;awssecuritygroup&quot; &quot;wireguard&quot; {<br>  name        = &quot;${local.vpc_name}-wireguard&quot;<br>  description = &quot;SG for WireGuard VPN Server&quot;<br>  vpcid      = data.awsvpc.vpc.id<br>  ingress {<br>    fromport   = local.wgport<br>    toport     = local.wgport<br>    protocol    = &quot;udp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>    description = &quot;Allow WireGuard Traffic&quot;<br>  }<br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>}</pre><p>Next we can setup a server and assing Elastic IP to it:</p><pre>resource &quot;aws_instance&quot; &quot;wireguard&quot; {<br>  count                       = 1<br>  ami                         = data.aws_ami.ubuntu.id<br>  instance_type               = &quot;t4g.nano&quot;<br>  subnetid                   = data.awssubnets.public.ids[0]<br>  vpcsecurity_group_ids      = [aws_securitygroup.wireguard.id]<br>  user_data                   = local.userdata<br>  userdata_replace_onchange = true<br>  tags                        = { Name = &quot;wireguard&quot; }<br>}<br> <br>resource &quot;awseipassociation&quot; &quot;wireguard&quot; {<br>  instanceid   = awsinstance.wireguard[0].id<br>  allocationid = awseip.wireguard.id<br>}</pre><h3>Client configuration</h3><p>To access to WireGuard server we need to have WireGuard <a href="https://www.wireguard.com/install/">client app</a> and valid client config with .conf extension.</p><p>We can generated this configs with Terraform Templates as well. So first, lets add new template file called client-conf.tpl:</p><pre>[Interface]<br>Address = ${client_addr}/32<br>PrivateKey = ${client_privkey}<br>DNS = ${client_dns}<br> <br>[Peer]<br>Endpoint = ${server_addr}<br>PublicKey = ${server_pubkey}<br>AllowedIPs = ${client_routes}<br>PersistentKeepalive = 25</pre><p>And add this code to generate client config to out terraform file:</p><pre># MARK: Export client configuration<br> <br>locals {<br>  # https://docs.aws.amazon.com/vpc/latest/userguide/AmazonDNS-concepts.html#AmazonDNS<br>  client_dns = [&quot;169.254.169.253&quot;, &quot;1.1.1.1&quot;, &quot;1.0.0.1&quot;]<br>  client_routes = [<br>    data.awsvpc.vpc.cidrblock, # All IPs in the VPC<br>    &quot;169.254.169.253/32&quot;,        # AWS DNS<br>    # &quot;0.0.0.0/32&quot;,                # Route all traffic through VPN (uncomment if you want this)<br>  ]<br>}<br> <br>resource &quot;localfile&quot; &quot;peerconf&quot; {<br>  foreach = { for index, p in local.secrets.wgpeers : p.name =&gt; p }<br>  filename = &quot;generated/${each.value.name}.conf&quot;<br>  content = templatefile(&quot;templates/client-conf.tpl&quot;, {<br>    serveraddr    = &quot;${aws_eip.wireguard.public_ip}:${local.wgport}&quot;,<br>    serverpubkey  = local.secrets.wgserver.pubkey,<br>    client_addr    = each.value.addr,<br>    client_privkey = each.value.privkey,<br>    clientdns     = join(&quot;,&quot;, local.clientdns),<br>    clientroutes  = join(&quot;,&quot;, local.clientroutes),<br>  })<br>}</pre><h3>Execute</h3><p>Finally we can run terraform init &amp; terraform apply. In less then a minute VPN server will be created and user client will be exported to generated/user1.conf. Then we can share this file with our teammates.</p><p>To check VPN connection working fine you can export .conf into WireGuard client. Then for example I check my RDS instance before VPN enabled and after.</p><pre>❯ dig +short my-rds.4oexsiqydp8q.us-east-1.rds.amazonaws.com<br>ec2-34-226-xx-xx.compute-1.amazonaws.com.<br>34.226.xx.xx<br> <br>❯ dig +short my-rds.4oexsiqydp8q.us-east-1.rds.amazonaws.com<br>ec2-34-226-xx-xx.compute-1.amazonaws.com.<br>10.10.20.80</pre><h3>Adding clients</h3><p>Adding new client configuration is quite simple. We need to generate new key pair:</p><pre>❯ bash -c &#39;priv=$(wg genkey); pub=$(echo $priv | wg pubkey); printf &quot;$priv\n$pub\n&quot;&#39;<br>ALqgaUiWd0rtcLza2K143x5RwS0Y5zwh3YwHx/L7nV0=<br>u1yQmh/G7n+S8aCp0PRuRuAuacmqYNzHLCPOcl9aS28=</pre><p>Then update secrets.yaml file:</p><pre>wg_peers:<br>  # ...<br>  - name: user2<br>    addr: 172.16.16.2<br>    privkey: ALqgaUiWd0rtcLza2K143x5RwS0Y5zwh3YwHx/L7nV0=<br>    pubkey: u1yQmh/G7n+S8aCp0PRuRuAuacmqYNzHLCPOcl9aS28=</pre><p>And run terraform apply again. Server will be re-created (!) with new configuration. Note that existing clients will be disconnected during deploy.</p><h3>Summary</h3><p>WireGuard provides easy solution for creating VPN server. We created cheap and fast setup to access to internal AWS VPC with ability to create different clients configurations, which can be shared with out team members.</p><p><em>PS. Source files of this article can be found </em><a href="https://github.com/vladkens/blog/tree/main/code/aws-wireguard-terraform/"><em>here</em></a><em>.</em></p><p><strong>Before You Go…</strong></p><ol><li>If you liked this article, <a href="https://medium.com/@vladkens/subscribe">subscribe</a> to get future updates.</li><li>Appreciate the content? Hold the clap button to give up to 50 claps!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3054cba21fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast multi-arch Docker build for Rust projects]]></title>
            <link>https://medium.com/@vladkens/fast-multi-arch-docker-build-for-rust-projects-a7db42f3adde?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7db42f3adde</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 01:05:43 GMT</pubDate>
            <atom:updated>2024-10-05T01:06:53.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eqpXe8pFhCqMBEH6W32Bg.png" /></figure><p>Rust allows programs to run very fast and memory efficient, but it has a cost — compile time. In web development, it is standard practice to deliver programs as Docker images and then run them in Kubernetes / <a href="https://medium.com/p/fdb9f6b7db07">Amazon ECS</a> / Docker Compose / etc. After the popularity of ARM processors in recent years, programmers have been faced with the additional step of preparing multi-arch Docker images (meaning that the same image should be able to run natively on both x86–64/amd64 and aarch64/arm64 processors).</p><p>Preparing Docker images for interpreted languages is usually not a problem — Docker Buildx is used, which in turn runs inside the emulator and builds the image for each architucture natively. NodeJS / Python just install dependencies via npm / pip, copy the project code, does a little polishing and that’s pretty much it. Even in compiled Go this approach works fine because Go has an extensive standard library. In the case of Rust, compiling even a simple web application is a rebuilding of the “universe” — almost any web application requires: HTTP-server, HTTP-client (which in turn requires a library to work with cryptography for https), asynchronous runtime (tokie, etc), serialization/desirialization (serde, serde_json); which in Rust should be installed as external libraries (crates) and should be compiled each time when program builded.</p><p>Although Rust compiler has a lot of work to do, it can do it quickly. Even not strongest CI, will build an average project in a couple of minutes. However, this is true only in case of building on native architecture (for example building amd64 binary on an amd64 processor). As soon as we need to build a multi-arch image, we have to do emulation and the compilation speed drops dramatically. For example, on my simple public project — <a href="https://github.com/vladkens/ghstats">ghstats</a>, building multi-arch image from scratch took about 50 minutes, when same build for native architecture takes 2–3 minutes.</p><p>Building time can be optimized by proper usage of Docker layers, so that the step with rebuilding dependencies occurs only when they are actually changed. So only the first build will be long and following builds will be fast. Unfortunately, Rust infrastructure have a problem in this point — any change in Cargo.toml file (for example version number) will invalidate Docker layer and triggers full rebuild of all dependencies.</p><h3>Problem definition</h3><p>So there are two problems with building multi-arch Docker images for Rust projects:</p><ol><li>Layer invalidation and full rebuild on any change in Cargo.toml</li><li>Very slow multi-arch build due to emulation</li></ol><h3>Better dependencies building</h3><p>Easiest way to solve the first problem is to use cargo-chef which was created exacly for it. cargo-chef converts Cargo.toml &amp; Cargo.lock into a special recipe.json file that will remain unchanged until project dependencies are unchanged. Then we can use this json file to cache expensive Docker layer that compiles dependencies.</p><p>Dockerfile with cargo-chef will use multi-stage build splited to 5 parts:</p><ol><li>Installing cargo-chef and build dependencies (OpenSSL, linux-headers, etc)</li><li>Preparing recipe.json file with project dependencies description</li><li>Installing &amp; builiding project dependencies from recipe.json</li><li>Building whole project</li><li>Copy binaries to runtime image and final polishing</li></ol><p>Example of Dockerfile with cargo-chef and multi-stage build (I use alpine in my projects, but you can use other base-images).</p><pre># (1) installing cargo-chef &amp; build deps<br>FROM rust:alpine AS chef<br>WORKDIR /app<br>RUN cargo install --locked cargo-chef<br>RUN apk add --no-cache musl-dev openssl-dev<br> <br># (2) prepating recipe file<br>FROM chef AS planner<br>COPY . .<br>RUN cargo chef prepare --recipe-path recipe.json<br> <br># (3) building project deps, cache magic happen on COPY command<br>FROM chef AS builder<br>COPY --from=planner /app/recipe.json recipe.json<br>RUN cargo chef cook --recipe-path recipe.json --release<br> <br># (4) actual project build<br>COPY . .<br>RUN cargo build -r<br> <br># (5) runtime image, you can use any base image you want<br>FROM alpine:latest AS runtime<br>WORKDIR /app<br>COPY --from=builder /app/target/release/prog /app/prog<br>CMD &quot;/app/prog&quot;</pre><p>This approach will speed up Docker image build many times while project dependencies are not changed. Because Docker builds stages separately, <em>planner</em> stage will be executed each time (but cargo-chef is fast!) and <em>builder</em> stage will be partially cached until recipe.json file are same.</p><p>If you need single architecture build this will work fine. But if you need multi-arch images, this approach still be slow.</p><h3>Multi-arch image with cross-compilation</h3><p>Multi-arch builds using Docker Buildx run very slow due to QEMU emulation. If we get rid of emulation, compilation will be at full speed. Rust has built-in cross-compilation for other architectures, so we adapt it in Docker build.</p><p>Cross-compilation in Rust itself works fine, but some crates are based on C libraries (OpenSSL, SQLite, etc). Compiling and linking C code is quite complicated and not always clear (usually you have to look for error codes somewhere on Stack Overflow or Github Issues until you get the right set of compilers/header files added). There is another tool that surprisingly solves the problem of cross-compiling C code very well — Zig (actually this is programming language, but they have build toolchain as well).</p><p>To connect Zig build toolchain with Rust I will use cargo-zigbuild crate. I other Docker file looks pretty same to our cargo-chef variant, expect I added second target in Cargo to build and cargo build replaced with cargo zigbuild.</p><pre># (1) this stage will be run always on current arch<br># zigbuild &amp; Cargo targets added<br>FROM --platform=$BUILDPLATFORM rust:alpine AS chef<br>WORKDIR /app<br>ENV PKGCONFIG_SYSROOTDIR=/<br>RUN apk add --no-cache musl-dev openssl-dev zig<br>RUN cargo install --locked cargo-zigbuild cargo-chef<br>RUN rustup target add x86_64-unknown-linux-musl aarch64-unknown-linux-musl<br> <br># (2) nothing changed<br>FROM chef AS planner<br>COPY . .<br>RUN cargo chef prepare --recipe-path recipe.json<br> <br># (3) building project deps: need to specify all targets; zigbuild used<br>FROM chef AS builder<br>COPY --from=planner /app/recipe.json recipe.json<br>RUN cargo chef cook --recipe-path recipe.json --release --zigbuild \<br>  --target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl<br> <br># (4) actuall project build for all targets<br># binary renamed to easier copy in runtime stage<br>COPY . .<br>RUN cargo zigbuild -r<br>    --target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl &amp;&amp; \<br>  mkdir /app/linux &amp;&amp; \<br>  cp target/aarch64-unknown-linux-musl/release/prog /app/linux/arm64 &amp;&amp; \<br>  cp target/x86_64-unknown-linux-musl/release/prog /app/linux/amd64<br> <br># (5) this staged will be emulated as was before<br># TARGETPLATFORM usage to copy right binary from builder stage<br># ARG populated by docker itself<br>FROM alpine:latest AS runtime<br>WORKDIR /app<br>ARG TARGETPLATFORM<br>COPY --from=builder /app/${TARGETPLATFORM} /app/prog<br>CMD &quot;/app/prog&quot;</pre><p>In general that all. Such build approach will work faster. For my project:</p><ol><li>initial build 50 min -&gt; 13 min (3.8x)</li><li>code updated 7 min -&gt; 3 min (2.3x)</li></ol><p>Additional performance can be achieved by moving first step into separate base image, then our main Docker image will not need to build cargo-zibguild and cargo-chef (-2 min from initial build).</p><p><strong>Before You Go…</strong></p><ol><li>If you liked this article, <a href="https://medium.com/@vladkens/subscribe">subscribe</a> to get future updates.</li><li>Appreciate the content? Hold the clap button to give up to 50 claps!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7db42f3adde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[apigen-ts — Simple TypeScript API Client Generator]]></title>
            <link>https://medium.com/@vladkens/apigen-ts-simple-typescript-api-client-generator-e32ff70b7d0d?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/e32ff70b7d0d</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 01:21:41 GMT</pubDate>
            <atom:updated>2024-09-04T01:22:46.547Z</atom:updated>
            <content:encoded><![CDATA[<h3>apigen-ts — Simple TypeScript API Client Generator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FWGiA0fQDtGlAEX4e4BbBg.png" /></figure><p>OpenAPI / Swagger is a good way to describe API contracts between backend / frontend or different services. Nowadays frontend is almost always TypeScript + some framework (React, Vue, Angular, etc). Backend in turn can be in NodeJS (and then in principle you can share contracts with code reuse), or in another language (e.g. Python / Go / Scala / Rust) and then code reuse and API synchronization becomes a problem.</p><p>OpenAPI can solve this problem through codegen — backend should qualitatively describe the available API methods and data types, after that you can use the client generation utility and get ready typed TypeScript code.</p><p>OpenAPI has a standard tool for such generation, but it has a number of problems:</p><ul><li>Tool is written in Java, which requires special software to be installed on dev computer / CI</li><li>Generate client is extensive and consists of many .ts files, which makes it not user friendly (in my opinion)</li></ul><p>In JavaScript ecosystem it is common to use npm (or yarn / pnpm — whatever you like more) as a package manager. But the point is the same: packages are written in JavaScript, installed from one place, versioned.</p><p>In npm you can find several alternative apigen utilities written in TypeScript which provides a better development experience. I used one of those too (swagger-typescript-api), until they changed interfaces a few times and I had to fix my several projects. I tried to find an alternative in npm, but all available generators (as of late 2023) also have their own problems: generate a lot of files, are difficult to configure, break compatibility between versions, require to install additional packages.</p><h3>Meet apigen-ts</h3><p>I have a couple of projects in NestJS / FastAPI in support mode, for which I just need a stable API client generation utility that is simple and won’t change often. So I wrote my own TypeScript HTTP API generation package from Swagger specification — <a href="https://github.com/vladkens/apigen-ts">apigen-ts</a>.</p><p>Originally I wrote apigen-ts for personal projects, but then I share it to my friends and they also started to use apigen-ts in their projects. Now I want to share it with the community, maybe it will be useful for someone too. So library features:</p><ul><li>supports Swagger / OpenAPI v2 / v3 / v3.1 (parsed with <a href="https://github.com/Redocly">redocly</a>)</li><li>generates a typed TypeScript client</li><li>single output file, single api class</li><li>exports data models for use in your code</li><li>automatic code formatting with prettier (peer dependency)</li><li>ability to <a href="https://medium.com/p/cf43554bd157">automatic dates parsing</a></li></ul><h3>Usage</h3><p>Usage is as simple as possible and is divided into two steps: generating a client from specification (local file or remote url; yaml or json), using the generated typed client in the app.</p><p>Generation of an arbitrary client can be performed by command:</p><pre>npx -y apigen-ts https://petstore3.swagger.io/api/v3/openapi.json ./api-client.ts</pre><p>Or you can install apigen-ts as a dev dependency (npm i -D apigen-ts) and create a task to generate the client in package.json:</p><pre>{<br>  &quot;name&quot;: &quot;my-frontend&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;apigen&quot;: &quot;apigen-ts http://127.0.0.1:3000/docs-json ./api-client.ts --parse-dates &amp;&amp; tsc --noEmit&quot;<br>  }<br>}</pre><p>Then use: npm run apigen or yarn apigen.</p><p>Generated file contains a client class named ApiClient and TypeScript types used in API endpoints. Next you can use them in app code in the following way:</p><pre>import { ApiClient, Pet } from &quot;./api-client&quot;;<br> <br>const api = new ApiClient({<br>  baseUrl: &quot;https://example.com&quot;,<br>  headers: { Authorization: &quot;secret-token&quot; },<br>});<br> <br>// GET https://example.com/pet/findByStatus?status=sold<br>await api.pet.findPetsByStatus({ status: &quot;sold&quot; }); // -&gt; Pet[]</pre><p>Generator tries to create method names in format like {domain}.{operation}. The types used in Swagger spec can be imported directly into code (in example above Pet is generated type). This approach makes it easy to track changes in contract and fix the application code where types are updated or methods are changed (of course if you describe your Swagger well). Just run new api generation and check frontend code for errors afterwards with TypeScript.</p><p>Also apigen-ts works well in CI pipelines, when on new commits to the backend part you run frontend api client generation and check code compatibility.</p><p>The generated client uses native fetch API (does not require additional packages) and can be used both in browser and NodeJS environment. If you use prettier in your project, the generated client will be automatically formatted according to project settings.</p><p>More configuration options and customization abilities can be in <a href="https://github.com/vladkens/apigen-ts">readme</a>.</p><h3>Conclusion</h3><p>Backend ↔ frontend (or backend ↔ backend) communication is monotonous and repetitive work from project to project. Do not waste time and effort on manual writing of api clients. Instead use simple tools to automate process and keep code quality.</p><p><strong>Before You Go…</strong></p><ol><li>If you liked this article, <a href="https://medium.com/@vladkens/subscribe">subscribe</a> to get future updates.</li><li>Appreciate the content? Hold the clap button to give up to 50 claps!</li><li>You can support the project with a star ⭐️ or leave an issue / feature request on <a href="https://github.com/vladkens/apigen-ts">Github page</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e32ff70b7d0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Table sorting and pagination with HTMX]]></title>
            <link>https://medium.com/@vladkens/table-sorting-and-pagination-with-htmx-7af8416f2b30?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/7af8416f2b30</guid>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 20:24:18 GMT</pubDate>
            <atom:updated>2024-10-08T22:26:32.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0FcTvDNHix3HM5L40SXJpw.png" /></figure><p>I recently tried HTMX for my new project — <a href="https://github.com/vladkens/ghstats">ghstats</a> — a dashboard of Github repository traffic in a single interface for longer than 14 days. This project was planned as a self-hosted service, so I was thinking about a really simple and memory-less tech stack. Last time I played with Rust, so I decided to use it instead of NodeJS / Python. Of course, if I’m generating static HTML on the server side, I have two options for implementing table sorting and pagination: use query parameters and do everything on backend, or use some JavaScript to call data from the backend and render the table on the client side. But HTMX offers a new, third way: write all the logic on the backend and replace the necessary parts of HTML with just a few tag attributes. Let’s see how it works.</p><h3>Initial setup</h3><p>To demonstrate table sorting and pagination, I’ll be using the same stack I used for my service: axum as a backend framework and maud for HTML templating (it&#39;s a DSL over Rust templates).</p><p>Let’s create new project with:</p><pre>cargo init htmx-example &amp;&amp; cd-html-example</pre><p>Then install dependencies:</p><pre>cargo add tokio axum maud --features tokio/full,maud/axum</pre><p>and do initial setup in src/main.rs file:</p><pre>use axum::{response::IntoResponse, routing::get, Router};<br>use maud::html;<br> <br>async fn index_page() -&gt; impl IntoResponse {<br>  html! {<br>    h1 { &quot;Hello, World!&quot; }<br>  }<br>}<br> <br>#[tokio::main]<br>async fn main() {<br>  let service = Router::new().route(&quot;/&quot;, get(indexpage)).into_makeservice();<br>  let listener = tokio::net::TcpListener::bind(&quot;127.0.0.1:8080&quot;).await.unwrap();<br>  axum::serve(listener, service).await.unwrap();<br>}</pre><p>Then we cant run this with cargo watch -x run and open http://127.0.0.1:8080 in the browser. &quot;Hello, World!&quot; should be displayed.</p><h3>Creating a static table</h3><p>Let’s add crates to generate random data:</p><pre>cargo add fake rand rand_chacha --features fake/derive</pre><p>and define simple Contact struct (like our application is simple CMS).</p><pre>use fake::faker::company::en::*;<br>use fake::faker::internet::en::*;<br>use fake::faker::name::en::*;<br>use fake::faker::phone_number::en::*;<br>use fake::{Dummy, Fake, Faker};<br>use rand::prelude::*;<br>use rand_chacha::ChaCha8Rng;<br> <br>#[derive(Debug, Clone, Dummy)]<br>struct Contact {<br>  id: u64,<br> <br>  #[dummy(faker = &quot;Name()&quot;)]<br>  name: String,<br> <br>  #[dummy(faker = &quot;CompanyName()&quot;)]<br>  company: String,<br> <br>  #[dummy(faker = &quot;FreeEmail()&quot;)]<br>  email: String,<br> <br>  #[dummy(faker = &quot;PhoneNumber()&quot;)]<br>  phone: String,<br>}<br> <br>fn get_contacts(n: usize) -&gt; Vec&lt;Contact&gt; {<br>  let mut items = Vec::with_capacity(n);<br>  let mut rng = ChaCha8Rng::seedfromu64(42);<br>  for _ in 0..n {<br>    items.push(Faker.fakewithrng(&amp;mut rng));<br>  }<br>  items<br>}<br> <br>async fn index_page() -&gt; impl IntoResponse {<br>    let contacts = get_contacts(100);<br>    println!(&quot;&gt;&gt; {:?}&quot;, contacts[0]);<br>    println!(&quot;&gt;&gt; {:?}&quot;, contacts[1]);<br> <br>  html! {<br>    h1 { &quot;Hello, World!&quot; }<br>  }<br>}</pre><p>Now on each request same random contacts will be generated, so we can use this data in our table. get_contacts function emulates database query in real environment.</p><p>I will also add base layout for page with <a href="https://picocss.com/">PicoCSS</a> framework to have nice look:</p><pre>fn base(html: maud::Markup) -&gt; impl IntoResponse {<br>  html! {<br>    html {<br>      head {<br>        meta charset=&quot;utf-8&quot; {}<br>        title { &quot;Contacts&quot; }<br> <br>        link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/@picocss/pico@2.0&quot; {}<br>        script src=&quot;https://unpkg.com/htmx.org@2.0&quot; {}<br>      }<br>      body class=&quot;container&quot; {<br>        { (html) }<br>      }<br>    }<br>  }<br>}</pre><p>And finally update index_page to render contact table:</p><pre>async fn index_page() -&gt; impl IntoResponse {<br>  let contacts = get_contacts(100);<br> <br>  base(html! {<br>    table {<br>      thead {<br>        tr {<br>          th { &quot;ID&quot; }<br>          th { &quot;Name&quot; }<br>          th { &quot;Company&quot; }<br>          th { &quot;Email&quot; }<br>          th { &quot;Phone&quot; }<br>        }<br>      }<br>      tbody {<br>        @for contact in contacts {<br>          tr {<br>            td { (contact.id) }<br>            td { (contact.name) }<br>            td { (contact.company) }<br>            td { (contact.email) }<br>            td { (contact.phone) }<br>          }<br>        }<br>      }<br>    }<br>  })<br>}</pre><p>We can request again http://127.0.0.1:8080 and see our table with random contacts (which on each request at same).</p><h3>Sorting table</h3><p>Now is the time to add sorting to our table. We will use HTMX to send requests to the server and get sorted HTML back. First, we need to add sorting logic to our backend. We will use query parameters to pass sorting column and direction.</p><p>To make it easier, I will add struct TableFilter which will represent sorting and pagination parameters, for code simplicity I will parse Request manually rather than using Query extractor and serde crate:</p><pre>use std::collections::HashMap;<br>use axum::extract::{Query, Request};<br> <br>#[derive(Debug)]<br>struct TableFilter {<br>  sort: String,<br>  order: String,<br>  page: u32,<br>  per_page: u32,<br>}<br> <br>fn parsetablefilter(req: &amp;Request) -&gt; TableFilter {<br>  let qs: Query&lt;HashMap&lt;String, String&gt;&gt; = Query::tryfromuri(req.uri()).unwrap();<br>  let sort = qs.get(&quot;sort&quot;).unwrapor(&amp;&quot;name&quot;.to_string()).tostring();<br>  let order = qs.get(&quot;order&quot;).unwrapor(&amp;&quot;desc&quot;.to_string()).tostring();<br>  let page = qs.get(&quot;page&quot;).unwrapor(&amp;&quot;1&quot;.tostring()).parse().unwrap();<br>  let perpage = qs.get(&quot;per_page&quot;).unwrap_or(&amp;&quot;10&quot;.tostring()).parse().unwrap();<br>  TableFilter { sort, order, page, per_page }<br>}</pre><p>Next, we need to create a function to render th with HTMX attributes to handle sorting:</p><pre>fn th(title: &amp;str, qs: &amp;TableFilter) -&gt; maud::Markup {<br>  let id = title.to_lowercase();<br>  let order = if qs.sort == id &amp;&amp; qs.order == &quot;desc&quot; { &quot;asc&quot; } else { &quot;desc&quot; };<br>  let url = format!(&quot;/?sort={}&amp;order={}&amp;page=1&amp;perpage={}&quot;, id, order, qs.perpage);<br> <br>  html! {<br>    th scope=&quot;col&quot; style=&quot;cursor: pointer;&quot;<br>      hx-trigger=&quot;click&quot;<br>      hx-get=(url)<br>      hx-target=&quot;#contacts_table&quot;<br>      hx-swap=&quot;outerHTML&quot;<br>    {<br>      (title)<br>      @if qs.sort == id {<br>        span style=&quot;margin-left: 0.5em;&quot; {<br>          @if qs.order == &quot;asc&quot; { &quot;↑&quot; } @else { &quot;↓&quot; }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Update get_contacts to accept TableFilter and sort items / do pagination:</p><pre>fn get_contacts(n: usize, qs: &amp;TableFilter) -&gt; (Vec&lt;Contact&gt;, u32) {<br>  let mut items: Vec&lt;Contact&gt; = Vec::with_capacity(n);<br>  let mut rng = ChaCha8Rng::seedfromu64(42);<br>  for _ in 0..n {<br>    items.push(Faker.fakewithrng(&amp;mut rng));<br>  }<br> <br>  items.sort_by(|a, b| {<br>    let cmp = match qs.sort.as_str() {<br>      &quot;id&quot; =&gt; a.id.cmp(&amp;b.id),<br>      &quot;name&quot; =&gt; a.name.cmp(&amp;b.name),<br>      &quot;company&quot; =&gt; a.company.cmp(&amp;b.company),<br>      &quot;email&quot; =&gt; a.email.cmp(&amp;b.email),<br>      &quot;phone&quot; =&gt; a.phone.cmp(&amp;b.phone),<br>      _ =&gt; a.id.cmp(&amp;b.id),<br>    };<br> <br>    if qs.order == &quot;asc&quot; {<br>      cmp<br>    } else {<br>      cmp.reverse()<br>    }<br>  });<br> <br>  let pages = (items.len() as f64 / qs.per_page as f64).ceil() as u32;<br>  let ranges = (qs.page as usize - 1) * qs.perpage as usize;<br>  let rangee = qs.page as usize * qs.perpage as usize;<br>  let items = items[ranges..range_e].tovec();<br> <br>  (items, pages)<br>}</pre><p>And finally, we can update our index_page to use TableFilter and th:</p><pre>async fn index_page(req: Request) -&gt; impl IntoResponse {<br>  let qs = parsetablefilter(&amp;req);<br>  let (contacts, pages) = get_contacts(100, &amp;qs);<br> <br>  base(html! {<br>      // id added to tell HTMX where to put new data<br>    table id=&quot;contacts_table&quot; {<br>      thead {<br>        tr {<br>          (th(&quot;ID&quot;, &amp;qs))<br>          (th(&quot;Name&quot;, &amp;qs))<br>          (th(&quot;Company&quot;, &amp;qs))<br>          (th(&quot;Email&quot;, &amp;qs))<br>          (th(&quot;Phone&quot;, &amp;qs))<br>        }<br>      }<br>      // same as before<br>    }<br>  })<br>}</pre><p>That’s it! Now we can sort our table by clicking on the column header. HTMX will send a request to the server with sorting parameters and replace the table with the new sorted data. Let’s me explain HTMX attributes:</p><ul><li>hx-trigger - event which will trigger the request, in our case it&#39;s click</li><li>hx-get - URL to send the request and HTTP method (can be GET or POST)</li><li>hx-target - CSS selector to replace with new data</li><li>hx-swap - how to replace the target, in our case it&#39;s outerHTML which will replace the whole table (by default it&#39;s inserting new data into the target)</li></ul><p>All this attributes handled automatically by HTMX, so we just need to include HTMX script in &lt;head&gt;.</p><h3>Pagination</h3><p>In previous step we already parse pagination filters to struct, so lets add code to render pagination links. I will use code from my another react project, which originally from StackOverflow answer:</p><pre>// https://stackoverflow.com/a/70263913<br>fn calc_pagination(page: usize, total: usize, len: usize) -&gt; Vec&lt;Option&lt;usize&gt;&gt; {<br>  use std::cmp::{max, min};<br> <br>  let len = if len == 0 { 5 } else { len };<br>  let total = max(total, page);<br>  let start =<br>    max(1, min(page as isize - ((len - 3) as isize / 2), total as isize - len as isize + 2))<br>      as usize;<br>  let end = min(total, max(page + (len - 2) / 2, len - 1));<br> <br>  let mut result = Vec::new();<br> <br>  if start &gt; 2 {<br>    result.push(Some(1));<br>    result.push(None);<br>  } else if start &gt; 1 {<br>    result.push(Some(1));<br>  }<br> <br>  for i in start..=end {<br>    result.push(Some(i));<br>  }<br> <br>  if end &lt; total - 1 {<br>    result.push(None);<br>    result.push(Some(total));<br>  } else if end &lt; total {<br>    result.push(Some(total));<br>  }<br> <br>  result<br>}</pre><p>Let’s define two more helper function which will render pagination link and delimiter (like ...):</p><pre>fn pagination_link(qs: &amp;TableFilter, i: u32) -&gt; maud::Markup {<br>  let url = format!(&quot;/?sort={}&amp;order={}&amp;page={}&amp;perpage={}&quot;, qs.sort, qs.order, i, qs.perpage);<br>  html! {<br>    li {<br>      a href=(url)<br>        hx-trigger=&quot;click&quot;<br>        hx-get=(url)<br>        hx-target=&quot;#contacts_table&quot;<br>        hx-swap=&quot;outerHTML&quot;<br>      { (i) }<br>    }<br>  }<br>}<br> <br>fn pagination_delim() -&gt; maud::Markup {<br>  html! {<br>    li {<br>      span { &quot;...&quot; }<br>    }<br>  }<br>}</pre><p>And finally we can write pagination function, which will return list of links and delimiters:</p><pre>fn pagination(pages: u32, qs: &amp;TableFilter) -&gt; maud::Markup {<br>  let items = calc_pagination(qs.page as usize, pages as usize, 5);<br> <br>  html!(<br>    nav {<br>      ul {<br>        @for item in items {<br>          @if let Some(i) = item {<br>            (pagination_link(qs, i as u32))<br>          } @else {<br>            (pagination_delim())<br>          }<br>        }<br>      }<br>    }<br>  )<br>}<br> <br>async fn index_page(req: Request) -&gt; impl IntoResponse {<br>    // ...<br>    base(html! {<br>        // ..<br>        // add pagination call after table<br>        (pagination(pages, &amp;qs))<br>    })<br>}</pre><h3>Partial HTML updates</h3><p>Before this step, we always replaced the whole page with new HTML content. This can be done without HTMX at all, so what the point of using it? It’s right, we have very simple layout before. Let’s make it more complex to show nice feature of HTMX — partial updates.</p><p>First of all let’s move table generation into separate function:</p><pre>fn getcontactstable(contacts: Vec&lt;Contact&gt;, qs: &amp;TableFilter, pages: u32) -&gt; maud::Markup {<br>  html! {<br>      // id moved from table to div<br>      div id=&quot;contacts_table&quot; {<br>        table {<br>          thead {<br>            tr {<br>              (th(&quot;ID&quot;, &amp;qs))<br>              (th(&quot;Name&quot;, &amp;qs))<br>              (th(&quot;Company&quot;, &amp;qs))<br>              (th(&quot;Email&quot;, &amp;qs))<br>              (th(&quot;Phone&quot;, &amp;qs))<br>            }<br>          }<br>          tbody {<br>            @for contact in contacts {<br>              tr {<br>                td { (contact.id) }<br>                td { (contact.name) }<br>                td { (contact.company) }<br>                td { (contact.email) }<br>                td { (contact.phone) }<br>              }<br>            }<br>          }<br>        }<br> <br>        (pagination(pages, &amp;qs))<br>       }<br>  }<br>}</pre><p>Now we can call this code in any other place and have contacts table. Now let’s add some navigation and other content to our main page:</p><pre>async fn index_page(req: Request) -&gt; impl IntoResponse {<br>  let qs = parsetablefilter(req);<br>  let (contacts, pages) = get_contacts(1000, &amp;qs);<br> <br>  base(html! {<br>    nav {<br>      ul {<br>        li { a href=&quot;/dashboard&quot; { &quot;Dashboard&quot; } }<br>        li { a href=&quot;/&quot; { &quot;Contacts&quot; } }<br>        li { a href=&quot;/settings&quot; { &quot;Settings&quot; } }<br>      }<br>    }<br> <br>    h1 { &quot;Contacts&quot; }<br>    (getcontactstable(contacts, &amp;qs, pages))<br>  })<br>}</pre><p>Right now in the application we have a simple navigation. But when we interact with the table, a full page will be returned, and the result will look like a nested page in a nested page… This is wrong. Let’s fix this with HTMX (and this is actually where HTMX comes power).</p><p>When browser loads the page it load as regular page with default headers. When request send by HTMX it will set extra headers like HX-Request and HX-Target. We can use this headers to detect which part of HTML should be returned. Let&#39;s add this code to our index_page:</p><pre>fn gethxtarget(req: &amp;Request) -&gt; Option&lt;&amp;str&gt; {<br>  match req.headers().get(&quot;hx-target&quot;) {<br>    Some(x) =&gt; Some(x.tostr().unwrap_ordefault()),<br>    None =&gt; None,<br>  }<br>}<br> <br>async fn index_page(req: Request) -&gt; impl IntoResponse {<br>  let qs = parsetablefilter(&amp;req);<br>  let (contacts, pages) = get_contacts(1000, &amp;qs);<br> <br>  match gethxtarget(&amp;req) {<br>    Some(&quot;contactstable&quot;) =&gt; return get_contacts_table(contacts, &amp;qs, pages).intoresponse(),<br>    _ =&gt; {}<br>  }<br> <br>  base(html! {<br>      // ... this part is the same<br>  })<br>  .intoresponse() // added intoresponse() to relax rust type inference<br>}</pre><p>So in this code we check if hx-target header is present. If not – we return full page. If it&#39;s present and equal to contacts_table – we return only table. This is how partial updates works in HTMX. We can split page to smaller parts and update it independently.</p><p><em>PS. Source files of this article can be found </em><a href="https://github.com/vladkens/blog/tree/main/code/rust-htmx-table-sorting"><em>here</em></a><em>.</em></p><h3>Conclusion</h3><p>HTMX is good utility for simple application which allows to add some interactivity without writing a lot of JavaScript code. It easy to use and can be integrated with any backend language, because not require any special server-side support. It’s also very lightweight and can be used in any project without any additional dependencies.</p><p><strong>Before You Go…</strong></p><ol><li>If you liked this article, <a href="https://medium.com/@vladkens/subscribe">subscribe</a> to get future updates.</li><li>Appreciate the content? Hold the clap button to give up to 50 claps!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7af8416f2b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get macOS power metrics with Rust?]]></title>
            <link>https://medium.com/@vladkens/how-to-get-macos-power-metrics-with-rust-d42b0ad53967?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/d42b0ad53967</guid>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 12:01:39 GMT</pubDate>
            <atom:updated>2024-08-13T12:01:39.056Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting CPU / GPU frequencies, energy usage &amp; temperature metrics using undocumented Apple API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtwgJOkYj79Z0tM4LeTj3Q.png" /></figure><p>In this post, I’m going to talk about how <a href="https://medium.com/@vladkens/mac-usage-monitor-in-terminal-meet-macmon-3a3391995224">macmon</a> works, specifically where it gets system metrics.</p><p>MacOS has a built-in powermetics utility that can show the current CPU core frequencies, utilisation, and power consumption. This program should take these values from the system somewhere. So the first thing to check is what shared libraries and function calls (symbols) are used.</p><p>There are several programs can do this:</p><ul><li>otool — show list of shared libraries</li><li>nm — see the list of used symbols</li><li>strings — just prints all strings from a binary file, but it may be useful to understand what is going on in the program.</li></ul><pre>&gt; otool -L /usr/bin/powermetrics<br> /usr/lib/libIOReport.dylib (compatibility version 1.0.0, current version 1.0.0)<br> /usr/lib/libpmsample.dylib (compatibility version 1.0.0, current version 2.0.0)<br> /usr/lib/libpmenergy.dylib (compatibility version 1.0.0, current version 2.0.0)<br> /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0, current version 275.0.0)<br>...<br><br>&gt; nm -a /usr/bin/powermetrics<br>/usr/bin/powermetrics (for architecture arm64e):<br>  ...<br>  U _IOPMCopyPowerStateInfo<br>  U _IORegistryEntryCreateCFProperties<br>  U _IORegistryEntryCreateCFProperty<br>  U _IORegistryEntryFromPath<br>  ...</pre><p>This data provides some starting point. Next I just did a search on Github to see how these libs might have been used in other repositories.</p><h4>Getting CPU / GPU Usage</h4><p>The first thing I found is that macOS has an IOReport shared library that returns a lot of hardware information. Including it can do sampling and return CPU/GPU &amp; energy usage.</p><p>IOReport operates on a subscription basis. It is possible to select interesting data channels (or all available) and perform sampling on it in order to obtain actual metrics. The channel has a group / subgroup name (sometimes may not exist). I’m interesting in “Energy Model”, “CPU Stats” / “CPU Core Performance States” and “GPU Stats” / “GPU Performance States”. These values were found by comparing available channels names with the list of those strings used in powermetrics (strings /usr/bin/powermetrics).</p><p>To subscribe to a channel and receive updates, it is first necessary to get internal channel struct as CFDictionary using IOReportCopyChannelsInGroup and merge all the dicts into one using IOReportMergeChannels. Then merged dictionary can be used to create an subscription using IOReportCreateSubscription. Once subscription object obtained, updates can be received with IOReportCreateSamples and IOReportCreateSamplesDelta. All together it looks something like this:</p><pre>// simplified code without error handling<br>use std::ptr::null;<br><br>let mut channels = vec![];<br>channels.push(IOReportCopyChannelsInGroup(&quot;Energy Model&quot;, null(), 0, 0, 0));<br>channels.push(IOReportCopyChannelsInGroup(&quot;CPU Stats&quot;, &quot;CPU Core Performance States&quot;, 0, 0, 0));<br><br>let chan = channels[0];<br>for i in 1..channels.len() {<br>  IOReportMergeChannels(chan, channels[i], null());<br>}<br><br>let size = CFDictionaryGetCount(chan);<br>let chan = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, size, chan);<br><br>let mut subs: MaybeUninit&lt;CFMutableDictionaryRef&gt; = MaybeUninit::uninit();<br>IOReportCreateSubscription(std::ptr::null(), chan, s.as_mut_ptr(), 0, std::ptr::null());<br>subs.assume_init();<br><br>let sample1 = IOReportCreateSamples(subs, chan, null());<br>std::thread::sleep(std::time::Duration::from_millis(100)); // 100ms<br>let sample2 = IOReportCreateSamples(subs, chan, null());<br><br>let rs = IOReportCreateSamplesDelta(sample1, sample2, null());<br>CFShow(rs);<br><br>// rs is CFDictionary, so we can read metrics by keys from it</pre><p>The basic dict functions are exported from <a href="https://crates.io/crates/core-foundation">core_foundation</a> crate. IOReport functions are C-bindings to a private macOS API:</p><pre>#[link(name = &quot;IOReport&quot;, kind = &quot;dylib&quot;)]<br>extern &quot;C&quot; {<br>  fn IOReportCopyChannelsInGroup(a: CFStringRef, b: CFStringRef, c: u64, d: u64, e: u64) -&gt; CFDictionaryRef;<br>  fn IOReportMergeChannels(a: CFDictionaryRef, b: CFDictionaryRef, nil: CFTypeRef);<br>  fn IOReportCreateSubscription(a: CVoidRef, b: CFMutableDictionaryRef, c: *mut CFMutableDictionaryRef, d: u64, b: CFTypeRef) -&gt; IOReportSubscriptionRef;<br>  fn IOReportCreateSamples(a: IOReportSubscriptionRef, b: CFMutableDictionaryRef, c: CFTypeRef) -&gt; CFDictionaryRef;<br>  fn IOReportCreateSamplesDelta(a: CFDictionaryRef, b: CFDictionaryRef, c: CFTypeRef) -&gt; CFDictionaryRef;<br>}</pre><p>Full implementation can be found <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/sources.rs#L478">here</a>.</p><p><em>Note: For CPU I get values separately for each core. In general, there is also a group “CPU Complex Performance States” to get values for the whole cluster at once, but the group results sometimes show 100% load of the cluster, when in reality there is no load. This is caused by some internal bug. For GPU there is no information for each core separately, so the load information is obtained for the whole GPU at once — good luck no errors were noticed.</em></p><h4>Parsing CPU / GPU Usage</h4><p>IOReportCreateSamplesDelta returns an object with one IOReportChannels field, which containts array of metrics objects. Each metrics object have group and subgroup (on which subscription was created), and extra fields: channel name, value unit and value itself.</p><p>The values for “CPU Stats” / “GPU Stats” are returned in array of tuples (string, int):</p><ul><li>string: frequency level name (first always IDLE)</li><li>int: time been on this level (should be in nanoseconds, but not sure)</li></ul><p>In general, internally CPU can work at different frequencies and voltages. The values of these frequencies are known in advance and are always the same. Under load CPU works at higher levels (higher frequency, higher voltage). During idle work it constantly jumps between modes (in any case OS always has some background activity). Simple tasks are mostly executed on E-cluster, more complex ones are switched to P-cluster.</p><p>Each cluster has different DVFS config (Dynamic Voltage and Frequency Scaling), but all cores within same cluster uses same DVFS config. Same approach is used for GPUs.</p><p>Usually GUI interfaces show single number as current core frequency, but in reality it is calculated as average of time each core work on DVFS level. So the average frequency of a core can be calculated like this:</p><pre>// predefined DVFS values for E-cluster<br>let frequencies = [600, 912, 1284, 1752, 2004, 2256, 2424]; // 7 items<br>// time was on each level (first value is idle)<br>let residencies = [17563069, 0, 5787276, 156965, 419037, 100647, 106031, 41735]; // 8 items<br><br>let total_time = residencies.iter().sum::&lt;u64&gt;();<br>let usage_time = residencies.iter().skip(1).sum::&lt;u64&gt;();<br><br>let mut freq = 0f64;<br>for i in 0..frequencies.len() {<br> let percent = residencies[i + 1] as f64 / usage_time as f64;<br> freq += percent * frequencies[i] as f64;<br>}<br><br>println!(&quot;E-cluster freq: {:.2} MHz&quot;, freq);</pre><p>DVFS values for target system can be read from AppleARMIODevice . Full code can be found <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/sources.rs#L459">here</a>. For M1/M2/M3 processors looks names are: voltage-states1-sram for E-Cluster, voltage-states5-sram for P-Cluster and voltage-states9 for GPU. For Max / Ultra chips is also exists voltage-states11-sram or something like this, because this chips have two or more P-Clusters but fortunately this values are same for all clusters of same group (at least for now).</p><h4>Parsing Energy Usage</h4><p>In the channel earlier, we also asked for metrics for the “Energy Model” group. These are easier to read because it’s just a number. Value unit can be mJ / uJ / nJ, so it just needs to be converted to Watts. This is easily done using the formula: P(W) = E(J) / t(s), where s is sampling time. Full code <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/metrics.rs#L249">here</a>.</p><pre>let joules_raw = IOReportSimpleGetIntegerValue(metric_dict, 0) as f32;<br>let joules = match metric_unit.as_str() {<br>  &quot;mJ&quot; =&gt; joules_raw / 1e3f32,<br>  &quot;uJ&quot; =&gt; joules_raw / 1e6f32,<br>  &quot;nJ&quot; =&gt; joules_raw / 1e9f32,<br>  _ =&gt; Err(format!(&quot;Unknown energy unit: {}&quot;, metric_unit).into()),<br>};<br><br>let sec = (duration as f32 / 1000.0);<br>let watts = joules / sec;</pre><h4>Getting RAM Usage</h4><p>Getting RAM / SWAP usage is done via libc in principle I think similar to any UNIX-like system. Nothing specific here, except to figure out how to calculate the value in bytes, since internally memory is measured in pages.</p><p>MacOS uses the <a href="https://opensource.apple.com/source/xnu/xnu-1456.1.26/osfmk/mach/vm_statistics.h.auto.html#:~:text=struct%20vm_statistics64">vm_statistics64</a> structure, which has quite a few fields. By experimentation I found a value that is similar to what Activity Monitor shows. To get current memory host_statistics64 need to be called. For total memory available and SWAP info sysconf call is enough. Full code can be found <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/sources.rs#L291">here</a>. Short example with <a href="https://crates.io/crates/libc">libc</a> crate:</p><pre>let mut count: u32 = libc::HOST_VM_INFO64_COUNT as _;<br>let mut stats = std::mem::zeroed::&lt;libc::vm_statistics64&gt;();<br><br>libc::host_statistics64(<br>  libc::mach_host_self(),<br>  libc::HOST_VM_INFO64,<br>  &amp;mut stats as *mut _ as *mut _, // cast to void (untyped) pointer<br>  &amp;mut count,<br>);<br><br>let page_size_kb = libc::sysconf(libc::_SC_PAGESIZE) as u64;<br>let usage = page_size_kb * (<br>  + stats.active_count as u64<br>  + stats.inactive_count as u64<br>  + stats.wire_count as u64<br>  + stats.speculative_count as u64<br>  + stats.compressor_page_count as u64<br>  - stats.purgeable_count as u64<br>  - stats.external_page_count as u64);</pre><h4>Getting Temperature Values</h4><p>This appeared to be the most complicated part of the program. Initially I wanted to get values for each core separately and show them in a separate tab in the interface. On macOS there are GUI programs (Stats, Macs Fan Control) that can do this, but after a detailed study I realised that the values in these programs are shown by guessing which sensor is responsible for which core.</p><p>Temperature value can be obtained from two places: IOHID for M1 on macOS 12–13 and SMC for M1/M2/M3 on macOS 14–15.</p><p>IOHID approach is simpler — it’s just a function call that returns a CFDictionary with values. There seems only <a href="https://github.com/freedomtan/sensors/blob/master/sensors/sensors.m">one person in open-source</a> who understands how it works, because all other repositories I found referenced it.</p><p>SMC (System Management Controller) is more complicated. It works through something similar to RPC calls with large structures where fields are optionally filled in depending on which RPC method called. SMC looks like a more classic approach, but it looks like Apple didn’t have time to implement all the functionality during migration to ARM architecture. To make macmon works everywhere, I had to implement both approaches.</p><p>IOHID implementation can be found <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/sources.rs#L603">here</a>, there is really nothing to talk about technically, except that the parameter values are found “magically”.</p><p>In SMC, it is possible to obtain a sensor’s value using a key. The key itself uses <a href="https://en.wikipedia.org/wiki/FourCC">FourCC</a> notation, which is essentially int32 but appears human-readable in code (for example, Tp01 -&gt; 0x54703031, Tp02 -&gt; 0x54703032, etc.). This key is used to obtain KeyInfo, from which KeyData can be retrieved. Therefore, to get the sensor value, two RPC calls are needed, which is inefficient and costly. Hence, it is necessary to cache the KeyInfo value beforehand.</p><p>The SMC initialisation process looks like: obtain all possible keys using the special key #KEY (0x234b4559), then filter out only those KeyInfo that start with Tp (CPU related) and Tg (GPU related), and then make requests only to them – resulting in one RPC call per sensor.</p><p>Since I do not know which sensors correspond to which core or other sensors on the chip, the program simply calculates average of all values per type.</p><p>SMC implementation can be found <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/sources.rs#L752">here</a> (utility to perform RPC calls), <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/metrics.rs#L83">here</a> (initialisation) and <a href="https://github.com/vladkens/macmon/blob/v0.2.2/src/metrics.rs#L147">here</a> (actual metrics gathering).</p><h4>Combine all together</h4><p>There’s nothing special about this part. Once per second, the current metric values are obtained from sources described above. The only thing worth noting is that SMC is used by default, if its value is not available, then IOHID is used (fallback for M1 on macOS 13). Then these values are combined into a single structure and return to caller.</p><p>Then these values are aggregated in the “frontend” code and output to the console using <a href="https://crates.io/crates/ratatui/">ratatui</a> crate or in plain text in raw mode. But this is already a material for a separate article.</p><p>You can try <a href="https://github.com/vladkens/macmon">macmon</a> with Homebrew:</p><pre>brew install vladkens/tap/macmon</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d42b0ad53967" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mac Usage Monitor in Terminal: Meet “macmon”]]></title>
            <link>https://medium.com/@vladkens/mac-usage-monitor-in-terminal-meet-macmon-3a3391995224?source=rss-4d50a0a8b26------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a3391995224</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[vladkens]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 12:01:43 GMT</pubDate>
            <atom:updated>2024-08-06T12:01:43.009Z</atom:updated>
            <content:encoded><![CDATA[<h3>Meet “macmon”: Mac Usage Monitor in Terminal</h3><h4>A TUI program that helps to monitor resource usage in real time</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfmtLMsfaoH0btUFgOFWfA.png" /></figure><p>When MacBook moved to ARM architecture (M1 processor), old system APIs stopped working and with them existing monitoring tools. However, macOS has a built-in console utility called powermetrics. It can show real-time resource consumption, but it does it in plain text.</p><p>Asitop is the first utility that allows users to view resource and energy consumption visually in a terminal. But it works on top of powermetrics which requires sudo to work. The program is written in Python and has compatibility issues with new M-processors.</p><p>macmon attempts to solve these issues. Coded in Rust as a single binary file it uses an undocumented Apple API (the same API that uses powermetrics, but doesn’t require sudo) to get metrics on system utilization, power consumption and temperature.</p><h4>Installation</h4><pre>brew install vladkens/tap/macmon</pre><h4>Features</h4><ul><li><strong>No Sudo Required:</strong> Run seamlessly without administrative privileges.</li><li><strong>Real-Time Metrics:</strong> Monitor CPU/GPU/ANE power usage live.</li><li><strong>Detailed Utilisation:</strong> Track CPU usage per cluster and RAM/Swap usage.</li><li><strong>Historical Data:</strong> View historical charts with average and max values.</li><li><strong>Customizable Interface:</strong> Switch between six color variants.</li><li><strong>Compact Design:</strong> Fits neatly in a small terminal window.</li><li><strong>Built with Rust:</strong> Ensuring performance and reliability.</li></ul><h4>Interface Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lRFbFU1kyW2TdokS" /></figure><p>The top line shows the chip model, number of Effective (E) and Performance (P) cores, number of GPU cores, and RAM.</p><p>The second line shows the chart of E and P cluster utilization of the CPU. MacOS uses E-cores for normal tasks, but when something complex needs to be done, process switches to P-cores.</p><p>The third line shows memory usage and GPU loading (during gaming, video processing or LLM running 😈).</p><p>And finally, the fourth line, the most interesting one, shows the power consumption for compute tasks, by system in general and separately for CPU, GPU and ANE (Apple Neural Engine). It also shows the average temperature of CPU and GPU.</p><p>macmon is an open-source program. You can view, star, request features or report bugs on <a href="https://github.com/vladkens/macmon"><strong>Github</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a3391995224" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>