<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Ruby &amp; Beyond</title>
    <description>Igor Aleksandrov – Ruby engineer, Open Source contributor, JetRockets CTO and co-founder, Docker Captain and a proud father.</description>
    <link>https://igor.works/</link>
    <atom:link href="https://igor.works/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Sat, 21 Nov 2026 19:22:44 +0400</pubDate>
    <lastBuildDate>Sat, 21 Nov 2026 19:22:44 +0400</lastBuildDate>
    <generator>Jekyll v4.4.1</generator>
    
      <item>
        <title>How Tabletist is built: a native database client in Rust and egui</title>
        <description>&lt;p&gt;Tabletist is a database client for PostgreSQL, MySQL, SQLite and BigQuery. It is
written in Rust on egui, and it runs on Linux, macOS and Windows. This post
is about how it is built: the rules the compiler holds for me, the rules
tests hold by reading the source, how I test a GUI without a screen, and
where the code is still only as good as review.&lt;/p&gt;

&lt;p&gt;Everything quoted here is real code from the repository, linked at the
commit it came from.&lt;/p&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;why-native-and-what-it-costs&quot;&gt;Why native, and what it costs&lt;/h2&gt;

&lt;p&gt;When I moved to Omarchy, a Hyprland setup where everything is driven
from the keyboard and follows one theme, no database client felt at home
there. I wanted a
client that looks like the rest of my desktop on Omarchy, and like a Mac
app on my Mac.&lt;/p&gt;

&lt;p&gt;So I built one on egui, an immediate-mode GUI library for Rust, through
eframe, its app framework. There is no browser inside. One codebase builds
a binary for each of the three systems, and the window is drawn with
OpenGL:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/Cargo.toml#L50-L55&quot;&gt;Cargo.toml, lines 50 to 55&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-toml&quot;&gt;# The whole UI. glow keeps the binary and dependency tree small; a 2D table
# browser does not need wgpu. AccessKit exposes controls to screen readers and
# to the headless tests. `links` opens the About dialog&apos;s link to the source
# in the browser, through webbrowser: the one crate it adds, since its own
# (url, log, objc2) are in the tree already.
eframe = { version = &quot;0.36&quot;, default-features = false, features = [&quot;accesskit&quot;, &quot;default_fonts&quot;, &quot;glow&quot;, &quot;links&quot;, &quot;persistence&quot;, &quot;wayland&quot;, &quot;x11&quot;] }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Most dependencies in &lt;code&gt;Cargo.toml&lt;/code&gt; have a comment like that one, saying
why they are there.&lt;/p&gt;

&lt;p&gt;The binary is not tiny. The Linux x86_64 binary of v0.5.0 is 43.2 MiB
stripped, with SQLite and rustls inside it, and an 18.4 MiB &lt;code&gt;.tar.gz&lt;/code&gt;
download. It is quick to start and modest to run, though. On my machine
(a Ryzen AI MAX+ 395 on Omarchy), launched with the demo database, v0.5.0
commits its first frame in 108 ms and has the demo’s table drawn and
settled in 136 ms, the median of 20 warm runs. Idle on the demo it uses
131.7 MiB of RSS, 87.9 MiB of it PSS. The method, the raw runs, and the
same numbers for the AppImage and for cold starts are in
&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/contrib/measure/README.md&quot;&gt;&lt;code&gt;contrib/measure&lt;/code&gt;&lt;/a&gt;,
so anyone can take them again.&lt;/p&gt;

&lt;p&gt;The same code draws three looks: one for Windows, one for macOS, and
Omarchy’s, which is keyboard-first and follows the desktop’s theme and
font as it changes. On Linux outside Omarchy, the app draws the macOS
look with the Windows keys. The three are one list:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/theme.rs#L504&quot;&gt;crates/tabletist-core/src/theme.rs, line 504&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    pub const ALL: [Look; 3] = [Self::standard(), Self::macos(), Self::omarchy()];
&lt;/code&gt;&lt;/pre&gt;

&lt;figure class=&quot;not-prose my-8 grid grid-cols-1 justify-items-center py-2&quot;&gt;
  &lt;img src=&quot;https://igor.works/tabletist/assets/images/omarchy-table.webp&quot; alt=&quot;Tabletist in its Omarchy look: the Bookshop demo database&apos;s book_covers table, with the sidebar of tables on the left and the row panel on the right&quot; style=&quot;max-width: 100%&quot; /&gt;

  
  &lt;figcaption class=&quot;mt-2 block text-center text-sm text-gray-600&quot;&gt;
    Omarchy&apos;s look, on the Bookshop demo database.
  &lt;/figcaption&gt;
  
&lt;/figure&gt;

&lt;p&gt;The keys differ too. The Mac and Windows looks share one set of keys
(Ctrl for Cmd on Windows), and Omarchy has its own, closer to vim.&lt;/p&gt;

&lt;p&gt;egui gave me a lot for free, and some things not at all. In an
immediate-mode library every frame is a function call that draws
everything again. That makes a view easy to write and easy to test. It
also means text, keyboard focus and accessibility are mine to get right,
everywhere, every frame.&lt;/p&gt;

&lt;p&gt;Two rules came out of that. A view never names a font, a family or a size.
It names a role, and the role knows its face and size in each look:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/typography.rs#L64-L78&quot;&gt;src/typography.rs, lines 64 to 78&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;pub enum TextRole {
    // macOS, from the spec.
    UiBody,
    UiBodyStrong,
    TableTitle,
    ScreenTitle,
    DialogTitle,
    SectionLabel,
    Secondary,
    FieldLabel,
    ColumnType,
    GridCell,
    Json,
    Tag,
    Shortcut,
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That is the start of the list. There are 43 roles in all, and a view uses
them like this:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/ui/calendar.rs#L455&quot;&gt;src/ui/calendar.rs, line 455&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    let laid = Text::one(look, TextRole::UiBodySemibold, &amp;amp;title, palette.text).layout(ui.ctx());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second rule is that keyboard focus is drawn in one place, after
everything else, for whatever has the keyboard. A view that drew its own
ring would sooner or later forget one:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/ui/focus.rs#L1-L4&quot;&gt;src/ui/focus.rs, lines 1 to 4&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;//! Keyboard focus, shown: a ring round whatever has the keyboard, once the
//! keyboard (not the pointer) put it there. One painter draws it for every
//! widget, egui&apos;s own included, so no Tab stop is ever without one; a
//! widget that wants another form than the default says so with [`hint`].
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I will be honest about these two: nothing but review enforces them. Today
no view outside &lt;code&gt;src/typography.rs&lt;/code&gt; builds a &lt;code&gt;FontId&lt;/code&gt; of its own or names
a &lt;code&gt;FontFamily&lt;/code&gt;, but no test would fail if one did. The rules below are the
ones I do not have to remember.&lt;/p&gt;

&lt;h2 id=&quot;rules-the-compiler-holds&quot;&gt;Rules the compiler holds&lt;/h2&gt;

&lt;p&gt;Where I can, a rule is a compile error. That holds for me, for anyone who
sends a pull request, and for a coding agent working in the repository.&lt;/p&gt;

&lt;h3 id=&quot;unsafe-lives-in-three-small-crates&quot;&gt;&lt;code&gt;unsafe&lt;/code&gt; lives in three small crates&lt;/h3&gt;

&lt;p&gt;The workspace forbids &lt;code&gt;unsafe&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/Cargo.toml#L13-L14&quot;&gt;Cargo.toml, lines 13 to 14&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-toml&quot;&gt;[workspace.lints.rust]
unsafe_code = &quot;forbid&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some calls cannot be made without it. CoreText lists the installed fonts
through C statics and untyped collections. The macOS menu bar needs an
Objective-C delegate for &lt;code&gt;NSMenu&lt;/code&gt;, and on Windows muda attaches the bar by
subclassing the window, a call it marks unsafe. SQLite hands back column
names as bytes that may not be UTF-8, and its authorizer is a C callback.&lt;/p&gt;

&lt;p&gt;Those calls live in three crates: &lt;code&gt;tabletist-appkit&lt;/code&gt; (the CoreText fonts,
despite the name), &lt;code&gt;tabletist-menubar&lt;/code&gt; and &lt;code&gt;tabletist-sqlite-ffi&lt;/code&gt;. Each
one lowers the lint from &lt;code&gt;forbid&lt;/code&gt; to &lt;code&gt;deny&lt;/code&gt;, and says why in its manifest:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-sqlite-ffi/Cargo.toml#L9-L23&quot;&gt;crates/tabletist-sqlite-ffi/Cargo.toml, lines 9 to 23&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-toml&quot;&gt;# The workspace forbids unsafe code. rusqlite reads a result column&apos;s name and
# declared type as `str` and panics when their bytes are not UTF-8, which a
# file can hold, and it keeps the statement&apos;s pointer to itself. Its
# authorizer reads the names SQLite asks about the same way. The bytes can
# only be read through SQLite&apos;s C API, so this crate carries the workspace&apos;s
# lints with `unsafe_code` lowered to `deny`, allowed only in the files that
# make those calls (`columns.rs`, `authorizer.rs` and the tests&apos; `testing.rs`),
# each use with a SAFETY note. The app and the database layer keep `forbid`.
[lints.rust]
unsafe_code = &quot;deny&quot;

[lints.clippy]
unwrap_used = &quot;warn&quot;
# An `unsafe` block or impl without a SAFETY note above it fails the build.
undocumented_unsafe_blocks = &quot;deny&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The difference between the two levels is the whole trick. An inner
&lt;code&gt;#[allow(unsafe_code)]&lt;/code&gt; cannot lift a &lt;code&gt;forbid&lt;/code&gt;: rustc refuses it. It can
lift a &lt;code&gt;deny&lt;/code&gt;. So in these three crates a file has to opt in with
&lt;code&gt;#![allow(unsafe_code)]&lt;/code&gt; at its top, and every other file in the crate
still cannot hold &lt;code&gt;unsafe&lt;/code&gt;. Six files opt in. Between them they hold 35
&lt;code&gt;unsafe&lt;/code&gt; blocks, 2 &lt;code&gt;unsafe impl&lt;/code&gt;s and 4 &lt;code&gt;unsafe fn&lt;/code&gt;s. The workspace’s
other four crates (the app, its core, the database layer and the MCP
server) hold none.&lt;/p&gt;

&lt;p&gt;Here is the one I find most interesting, from the SQLite authorizer. A
Rust closure goes to SQLite as a raw pointer, and the SAFETY notes are
where I keep track of who owns the box at each step:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-sqlite-ffi/src/authorizer.rs#L146-L186&quot;&gt;crates/tabletist-sqlite-ffi/src/authorizer.rs, lines 146 to 186&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;pub fn set_authorizer&amp;lt;F&amp;gt;(connection: &amp;amp;rusqlite::Connection, authorizer: F) -&amp;gt; rusqlite::Result&amp;lt;()&amp;gt;
where
    F: Fn(&amp;amp;Action&amp;lt;&apos;_&amp;gt;) -&amp;gt; Authorization + Send + &apos;static,
{
    // SAFETY: the handle is used only below, while `connection` is borrowed.
    // A connection is not `Sync`, so no other thread prepares a statement on
    // it meanwhile.
    let db = unsafe { connection.handle() };
    let callback = Box::into_raw(Box::new(authorizer)).cast::&amp;lt;c_void&amp;gt;();
    // SAFETY: `db` is an open connection. `ask::&amp;lt;F&amp;gt;` gets `callback`, which
    // points to an `F` that lives until `free::&amp;lt;F&amp;gt;` drops it, and that is
    // not before SQLite has stopped calling `ask::&amp;lt;F&amp;gt;` with it: see below.
    // `F` is `Send`, so it may be called on whichever thread the connection
    // moves to.
    let code = unsafe { ffi::sqlite3_set_authorizer(db, Some(ask::&amp;lt;F&amp;gt;), callback) };
    if code != ffi::SQLITE_OK {
        // SAFETY: SQLite did not take the pointer, so the box made above is
        // still this function&apos;s to free.
        drop(unsafe { Box::from_raw(callback.cast::&amp;lt;F&amp;gt;()) });
        return Err(failure(code, None));
    }
    // SAFETY: `db` is an open connection and the name is a NUL-terminated
    // string, which SQLite copies. SQLite calls `free::&amp;lt;F&amp;gt;` with `callback`
    // once: when other data is kept under the name or when the connection
    // closes. Either way nothing calls the authorizer by then: this function
    // and `remove_authorizer` point SQLite away from it first, and a closed
    // connection prepares nothing. The authorizer this one replaces is freed
    // here the same way, by the `free` it was kept with, after the call
    // above took it out of use.
    let code =
        unsafe { ffi::sqlite3_set_clientdata(db, KEPT_AS.as_ptr(), callback, Some(free::&amp;lt;F&amp;gt;)) };
    if code != ffi::SQLITE_OK {
        // SQLite frees what it cannot keep, so the callback is gone and
        // nothing may call it.
        // SAFETY: `db` is an open connection, and no callback with no
        // argument takes the authorizer off.
        unsafe { ffi::sqlite3_set_authorizer(db, None, ptr::null_mut()) };
        return Err(failure(code, None));
    }
    Ok(())
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Every &lt;code&gt;unsafe&lt;/code&gt; block in the three crates has a SAFETY note like these.
That is not left to memory either: the manifest above, like the other two,
denies &lt;code&gt;clippy::undocumented_unsafe_blocks&lt;/code&gt;, so an &lt;code&gt;unsafe&lt;/code&gt; block or impl
without a note fails the build.&lt;/p&gt;

&lt;h3 id=&quot;every-engine-is-decided-for&quot;&gt;Every engine is decided for&lt;/h3&gt;

&lt;p&gt;Tabletist speaks to four engines, and a lot of code depends on which. The
rule is that such code matches on &lt;code&gt;Driver&lt;/code&gt; or &lt;code&gt;Dialect&lt;/code&gt; and names every
variant:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-db/src/spec.rs#L11-L29&quot;&gt;crates/tabletist-db/src/spec.rs, lines 11 to 29&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = &quot;lowercase&quot;)]
pub enum Driver {
    #[default]
    Postgres,
    #[serde(rename = &quot;mysql&quot;)]
    MySql,
    Sqlite,
    BigQuery,
}

impl Driver {
    pub fn default_port(self) -&amp;gt; u16 {
        match self {
            Self::Postgres =&amp;gt; 5432,
            Self::MySql =&amp;gt; 3306,
            Self::Sqlite | Self::BigQuery =&amp;gt; 0,
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A new engine then fails to compile in every place like this, until
someone decides what it does there. That stopped being a thought
experiment when BigQuery came in as the fourth engine. BigQuery support
came from &lt;a href=&quot;https://github.com/brianstarke&quot;&gt;@brianstarke&lt;/a&gt;
(&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/pull/266&quot;&gt;#266&lt;/a&gt;), and every
match like the one above now has a BigQuery arm. The same goes for the enums
behind them. This is how the database layer runs an agent’s read:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-db/src/lib.rs#L304-L309&quot;&gt;crates/tabletist-db/src/lib.rs, lines 304 to 309&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;        let (outcome, masked) = match &amp;amp;self.inner {
            Inner::Sqlite(conn) =&amp;gt; conn.run_read(read, limits, sources, stop).await,
            Inner::Postgres(conn) =&amp;gt; conn.run_read(read, limits, sources, stop).await,
            Inner::MySql(conn) =&amp;gt; conn.run_read(read, limits, sources, stop).await,
            Inner::BigQuery(conn) =&amp;gt; conn.run_read(read, limits, sources, stop).await,
        }?;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;An &lt;code&gt;if driver == Driver::Sqlite&lt;/code&gt; would compile today and quietly give a
fifth engine the &lt;code&gt;else&lt;/code&gt; branch. The compiler cannot stop that, since
&lt;code&gt;Driver&lt;/code&gt; derives &lt;code&gt;PartialEq&lt;/code&gt;. A test does, in the next section.&lt;/p&gt;

&lt;h3 id=&quot;the-core-cannot-draw&quot;&gt;The core cannot draw&lt;/h3&gt;

&lt;p&gt;The app’s state and its edits, the backend, the settings and the keymap
live in their own crate, &lt;code&gt;tabletist-core&lt;/code&gt;. The app’s crate, with the views
and the window, stands on it. The core needs a few of egui’s data types,
but it must never draw. The compiler holds part of that: the core cannot
name the app’s crate, since it does not depend on it. A test holds the
rest:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/tests/interface.rs#L1-L8&quot;&gt;crates/tabletist-core/tests/interface.rs, lines 1 to 8&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;//! The core stays off the interface. It depends on egui for three data
//! types (`Key`, `Color32`, `FontData`), because fastframe-theme stands on
//! egui anyway, but it never draws: no crate of the window, the widgets or
//! the text they lay out in its `Cargo.toml`, and no `egui::Context`,
//! `egui::Ui`, `egui::Painter` or `egui::Response` in its sources, tests
//! included. What sets up egui or draws on it is the `tabletist` crate&apos;s.
//! That the core names nothing of the interface the compiler holds: this
//! crate does not depend on that one.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That test reads the core’s manifest and its sources as text, the way the
tests in the next section do. So nothing in the core, its own tests
included, can reach for a window, even by accident.&lt;/p&gt;

&lt;h3 id=&quot;a-key-is-something-only-the-keymap-can-write&quot;&gt;A key is something only the keymap can write&lt;/h3&gt;

&lt;p&gt;Every key in the app is in one table, &lt;code&gt;BINDINGS&lt;/code&gt; in
&lt;code&gt;crates/tabletist-core/src/keymap.rs&lt;/code&gt;: each
command, the scopes it holds in (the grid, the SQL editor, a dialog), and
its keys for the Mac look and for Omarchy. Windows takes the Mac’s keys
with Ctrl for Cmd, unless a line gives it keys of its own.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/keymap.rs#L1394-L1412&quot;&gt;crates/tabletist-core/src/keymap.rs, lines 1394 to 1412&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;pub const BINDINGS: &amp;amp;[Binding] = {
    use Command as C;
    &amp;amp;[
        // Window and connections.
        bind(
            C::Connections,
            GLOBAL,
            keys(&amp;amp;[k(&quot;cmd+o&quot;)]),
            // In a text field the chord is the field&apos;s copy: the only one
            // a cell&apos;s editor has, where Ctrl+C drops the edit.
            keys(&amp;amp;[k(&quot;ctrl+shift+c&quot;)]).normal(),
        ),
        bind(
            C::GoToConnectionWindow,
            GLOBAL,
            keys(&amp;amp;[k(&quot;cmd+1..9&quot;)]),
            keys(&amp;amp;[k(&quot;ctrl+shift+1..9&quot;)]),
        ),
        bind(C::SwitchDatabase, GLOBAL, NONE, keys(&amp;amp;[k(&quot;ctrl+shift+d&quot;)])),
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The table has 337 entries for 315 commands. A command that is not built yet
is in it too, with its keys, so nothing else can take them.&lt;/p&gt;

&lt;p&gt;Views do not compare key events. They ask the keymap whether a command’s
key went down. And whatever paints a key beside a word, like a hint in a
footer or a button’s shortcut, takes a &lt;code&gt;Written&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/keymap.rs#L3276-L3280&quot;&gt;crates/tabletist-core/src/keymap.rs, lines 3276 to 3280&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// A key as a layout writes it. Only the keymap makes one, so what paints
/// a key beside a word (a hint, a button&apos;s shortcut) can take nothing
/// written by hand.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Written(String);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Its field is private to the keymap module. A view cannot make one from a
string, so it cannot paint a key that the keymap did not write. When
someone rebinds a key in &lt;code&gt;settings.toml&lt;/code&gt;, every hint changes with it.&lt;/p&gt;

&lt;h2 id=&quot;rules-tests-hold-by-reading-the-source&quot;&gt;Rules tests hold by reading the source&lt;/h2&gt;

&lt;p&gt;Some rules the type system cannot say. For those I have tests that read the
&lt;code&gt;.rs&lt;/code&gt; files as text. There are three of them, and they share one habit:
each tests its own scan, so it cannot pass just by finding nothing.&lt;/p&gt;

&lt;h3 id=&quot;no-comparing-an-engine&quot;&gt;No comparing an engine&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;tests/engines.rs&lt;/code&gt; reads every Rust file of the app, its core, the
database layer and the MCP server. It drops comment lines and each file’s &lt;code&gt;tests&lt;/code&gt; module,
joins the rest onto one line so a comparison split over lines reads as
one, and looks for a variant compared with &lt;code&gt;==&lt;/code&gt;, &lt;code&gt;!=&lt;/code&gt; or inside
&lt;code&gt;matches!&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/tests/engines.rs#L195-L213&quot;&gt;tests/engines.rs, lines 195 to 213&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[test]
fn no_code_compares_a_driver_or_a_dialect() {
    // A comparison gives an engine added later the other side&apos;s answer
    // without anyone choosing it. A `match` that names every engine does
    // not compile until someone has.
    let found: Vec&amp;lt;String&amp;gt; = sources()
        .iter()
        .flat_map(|(path, text)| {
            comparisons(&amp;amp;code(text))
                .into_iter()
                .map(move |found| format!(&quot;{path}: {found}&quot;))
        })
        .collect();
    assert!(
        found.is_empty(),
        &quot;match on every engine instead:\n{}&quot;,
        found.join(&quot;\n&quot;)
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And here is part of the test of the scan itself. These are texts it has to
find:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/tests/engines.rs#L160-L173&quot;&gt;tests/engines.rs, lines 160 to 173&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[test]
fn the_scan_finds_each_way_to_compare() {
    for text in [
        &quot;if spec.driver == Driver::Sqlite {&quot;,
        &quot;let remote = tabletist_db::Driver::Sqlite != workspace.driver;&quot;,
        &quot;b&apos;#&apos; if dialect\n    == Dialect::MySql =&amp;gt; comment(),&quot;,
        &quot;if matches!(self.dialect, Dialect::Postgres | Dialect::Sqlite) {&quot;,
        &quot;if matches!(driver.dialect(), Dialect::MySql) {&quot;,
        &quot;if Dialect::Ms_Sql == dialect {&quot;,
        &quot;if driver == (Driver::Sqlite) {&quot;,
        &quot;if (Dialect::MySql) != dialect {&quot;,
        &quot;#[cfg(test)]\nmod helpers;\n\nfn file(driver: Driver) -&amp;gt; bool {\n    driver == Driver::Sqlite\n}&quot;,
        &quot;let file = saved.map(|saved| saved.driver) == Some(Driver::Sqlite);&quot;,
        &quot;if drivers.iter().any(|driver| driver == &amp;amp;Driver::Sqlite) {&quot;,
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It has holes, and I would rather list them than have someone find them in
the comments. A &lt;code&gt;_ =&amp;gt;&lt;/code&gt; arm is not caught: it compiles, and it gives a new
engine an answer nobody chose. A comparison written with &lt;code&gt;Self::&lt;/code&gt; inside
the enums’ own methods is not caught. And comparing two values with each
other, like &lt;code&gt;read.dialect() != self.dialect()&lt;/code&gt;, passes on purpose: a new
engine gets the right answer from it. The rule is about comparing with a
variant.&lt;/p&gt;

&lt;h3 id=&quot;no-key-spelled-by-hand&quot;&gt;No key spelled by hand&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;tests/keys.rs&lt;/code&gt; looks at every string literal in the app’s code (tests
and screenshot scenes aside) and fails on one that spells a key anywhere
but the keymap:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/tests/keys.rs#L12-L15&quot;&gt;tests/keys.rs, lines 12 to 15&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;const SPELLED: [&amp;amp;str; 18] = [
    &quot;ctrl+&quot;, &quot;Ctrl+&quot;, &quot;cmd+&quot;, &quot;Cmd+&quot;, &quot;Cmd/&quot;, &quot;alt+&quot;, &quot;Alt+&quot;, &quot;shift+&quot;, &quot;Shift+&quot;, &quot;Mod+&quot;, &quot;⌘&quot;, &quot;⇧&quot;,
    &quot;⌥&quot;, &quot;⌃&quot;, &quot;↩&quot;, &quot;⌫&quot;, &quot;⌦&quot;, &quot;⇥&quot;,
];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/tests/keys.rs#L151-L172&quot;&gt;tests/keys.rs, lines 151 to 172&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[test]
fn no_key_is_spelled_outside_the_keymap() {
    let mut found = Vec::new();
    for (name, text) in sources() {
        if MAY.contains(&amp;amp;name.as_str()) || TESTS.contains(&amp;amp;name.as_str()) {
            continue;
        }
        let code = tests_start(&amp;amp;text).map_or(text.as_str(), |at| &amp;amp;text[..at]);
        for (number, line) in code.lines().enumerate() {
            for literal in literals(line) {
                if SPELLED.iter().any(|spelled| literal.contains(spelled)) {
                    found.push(format!(&quot;{name}:{}: {literal:?}&quot;, number + 1));
                }
            }
        }
    }
    assert!(
        found.is_empty(),
        &quot;keys written by hand, where the keymap should be asked:\n{}&quot;,
        found.join(&quot;\n&quot;)
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This catches the usual slip, a tooltip that says “Cmd+F” in its own words.
It does not catch a bare &lt;code&gt;&quot;d&quot;&lt;/code&gt; or &lt;code&gt;&quot;Enter&quot;&lt;/code&gt;. That is what &lt;code&gt;Written&lt;/code&gt; is for.&lt;/p&gt;

&lt;p&gt;The keymap tests itself from its own data too. This one walks every pair
of entries, in every layout, and fails when two commands share a key where
both could be read: the same scope or scopes that hold together, the same
condition, and modes that overlap:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/keymap.rs#L4881-L4905&quot;&gt;crates/tabletist-core/src/keymap.rs, lines 4881 to 4905&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    #[test]
    fn no_two_commands_share_a_key_where_both_could_be_read() {
        let keymap = Keymap::default();
        for layout in Layout::ALL {
            let entries = entries(&amp;amp;keymap, layout);
            for (index, a) in entries.iter().enumerate() {
                for b in &amp;amp;entries[index + 1..] {
                    let together =
                        a.scope.alongside(b.scope) &amp;amp;&amp;amp; a.when == b.when &amp;amp;&amp;amp; a.mode.overlaps(b.mode);
                    assert!(
                        a.command == b.command
                            || !together
                            || !clash(layout, &amp;amp;a.spelled, &amp;amp;b.spelled),
                        &quot;{layout:?}: {} ({:?}, {}) and {} ({:?}, {})&quot;,
                        a.keys,
                        a.command,
                        a.scope.id(),
                        b.keys,
                        b.command,
                        b.scope.id(),
                    );
                }
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;clash&lt;/code&gt; knows that &lt;code&gt;y&lt;/code&gt; clashes with &lt;code&gt;yy p&lt;/code&gt; (one is the start of the other),
that &lt;code&gt;alt+3&lt;/code&gt; clashes with &lt;code&gt;alt+1..9&lt;/code&gt;, and that on Windows &lt;code&gt;cmd+t&lt;/code&gt; and
&lt;code&gt;ctrl+t&lt;/code&gt; are the same key. Two commands sharing a key is a failing test
with both names in it, not a bug report.&lt;/p&gt;

&lt;h3 id=&quot;the-mcp-server-never-names-a-secret&quot;&gt;The MCP server never names a secret&lt;/h3&gt;

&lt;p&gt;The third one is in the MCP server’s crate, and it is the shortest:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-mcp/tests/secrets.rs#L225-L249&quot;&gt;crates/tabletist-mcp/tests/secrets.rs, lines 225 to 249&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;#[test]
fn the_crate_never_names_what_opens_a_database() {
    let mut files = Vec::new();
    sources(
        &amp;amp;Path::new(env!(&quot;CARGO_MANIFEST_DIR&quot;)).join(&quot;src&quot;),
        &amp;amp;mut files,
    );
    assert!(files.len() &amp;gt;= 8, &quot;{files:?}&quot;);
    for file in files {
        let text = std::fs::read_to_string(&amp;amp;file).unwrap();
        for name in [
            &quot;ConnectSpec&quot;,
            &quot;Secrets&quot;,
            &quot;HostKeys&quot;,
            &quot;connect_with&quot;,
            &quot;Connection::connect&quot;,
        ] {
            assert!(
                !text.contains(name),
                &quot;{} names {name}: the server reaches a database through its gateway alone&quot;,
                file.display()
            );
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;More on why in the MCP section.&lt;/p&gt;

&lt;h2 id=&quot;testing-a-gui-without-a-screen&quot;&gt;Testing a GUI without a screen&lt;/h2&gt;

&lt;p&gt;egui can run a frame without a window: you hand &lt;code&gt;egui::Context::run_ui&lt;/code&gt; the
input for one frame, and you get back what it painted and, with AccessKit
on, the accessibility tree a screen reader would see. My test harness,
&lt;code&gt;src/testing.rs&lt;/code&gt;, runs the whole app that way. A test clicks a control by
its accessible name, the way a screen reader asks for one:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/testing.rs#L283-L308&quot;&gt;src/testing.rs, lines 283 to 308&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    /// Clicks the widget labelled `label` through AccessKit: a button if
    /// there is one, else the sidebar&apos;s row of that table, view or group,
    /// else any node with that label (selectable labels and toggles get
    /// other roles).
    pub fn click(&amp;amp;mut self, label: &amp;amp;str) {
        let tree = self.settle();
        let target = node(&amp;amp;tree, label, Role::Button)
            .or_else(|| tree_row(&amp;amp;tree, label))
            .or_else(|| node(&amp;amp;tree, label, Role::Tab))
            .or_else(|| {
                tree.nodes
                    .iter()
                    .find(|(_, node)| node.label() == Some(label))
                    .map(|(id, _)| *id)
            })
            .unwrap_or_else(|| panic!(&quot;nothing labelled {label:?}: {:?}&quot;, labels(&amp;amp;tree)));
        self.frame(vec![egui::Event::AccessKitActionRequest(
            accesskit::ActionRequest {
                target_tree: accesskit::TreeId::ROOT,
                target_node: target,
                action: accesskit::Action::Click,
                data: None,
            },
        )]);
        self.settle();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Key presses go in as egui events, one frame with the key down and one with
it up. The harness also keeps what the last frame painted (each piece of
text with its colour and place), so a test can check that a hint is drawn
in the right colour too.&lt;/p&gt;

&lt;p&gt;The harness never connects to a database. The app’s backend normally runs
on its own thread; in tests it is one that records:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/backend.rs#L688-L711&quot;&gt;crates/tabletist-core/src/backend.rs, lines 688 to 711&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    /// A backend with no thread: commands are recorded, events are injected.
    /// For reducer and UI tests.
    pub fn recording() -&amp;gt; Self {
        let (event_tx, event_rx) = mpsc::channel();
        Self {
            commands: None,
            events: event_rx,
            runtime: None,
            outbox: Outbox {
                events: event_tx,
                waker: Waker::default(),
            },
            #[cfg(any(test, feature = &quot;testing&quot;))]
            sent: Vec::new(),
            #[cfg(any(test, feature = &quot;testing&quot;))]
            saves: Vec::new(),
            #[cfg(any(test, feature = &quot;testing&quot;))]
            exports: Vec::new(),
            #[cfg(any(test, feature = &quot;testing&quot;))]
            export_asks: Vec::new(),
            #[cfg(test)]
            watched: Watched::default(),
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A UI test checks which commands the app sent, and hands it the events a
database would have sent back. The engines have their own integration
tests, against real PostgreSQL, MySQL and MariaDB servers, which CI runs
on Linux.&lt;/p&gt;

&lt;p&gt;Here is a whole test. It opens the connection picker with one saved
connection, then deletes it two ways (from the row’s menu, and from the
connection’s form) and checks that both ask first. It runs once for each
desktop look:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/ui/mod.rs#L3524-L3542&quot;&gt;src/ui/mod.rs, lines 3524 to 3542&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    #[test]
    fn a_rows_menu_and_the_connection_form_ask_before_deleting() {
        for look in desktop_looks() {
            // The row&apos;s menu.
            let mut harness = picker_with_one(look);
            harness.click(&quot;More actions for Bookshop&quot;);
            harness.click(&quot;Delete&quot;);
            assert!(asks_to_delete(&amp;amp;harness), &quot;{}: the menu&quot;, look.name);
            assert_eq!(saved(&amp;amp;harness), 1, &quot;{}: the menu&quot;, look.name);
            // The form&apos;s Delete closes the form, and the picker asks.
            let mut harness = picker_with_one(look);
            let conn = harness.app.connections.connections[0].id.clone();
            harness.app.apply(Action::EditConnection(conn));
            harness.click(&quot;Delete Bookshop&quot;);
            assert!(harness.app.dialog.is_none(), &quot;{}&quot;, look.name);
            assert!(asks_to_delete(&amp;amp;harness), &quot;{}: the form&quot;, look.name);
            assert_eq!(saved(&amp;amp;harness), 1, &quot;{}: the form&quot;, look.name);
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;asks_to_delete&lt;/code&gt; reads the app’s state:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/ui/mod.rs#L3190-L3196&quot;&gt;src/ui/mod.rs, lines 3190 to 3196&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    /// Whether the picker asks whether to delete a connection.
    fn asks_to_delete(harness: &amp;amp;Harness) -&amp;gt; bool {
        matches!(
            &amp;amp;harness.app.active_tab().content,
            crate::model::ConnTabContent::Picker(picker) if picker.deleting.is_some()
        )
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So the clicks go through AccessKit, by name, and the checks read the app.
A test that only reads the accessibility tree is possible too, but I don’t
pretend every test is a screen reader test. What I get from this is that
every control a test can click has a name and a role, and a control
without one fails a test the day it is added.&lt;/p&gt;

&lt;p&gt;The suite has 5,363 tests at v0.7.0, and 2,267 of them are the views’ own,
in &lt;code&gt;src/ui&lt;/code&gt;. CI runs them all on Linux, macOS and Windows.&lt;/p&gt;

&lt;h2 id=&quot;views-push-actions-the-app-applies-them&quot;&gt;Views push actions, the app applies them&lt;/h2&gt;

&lt;p&gt;A view in Tabletist does not change the application’s state. It pushes an
&lt;code&gt;Action&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/model.rs#L50-L65&quot;&gt;crates/tabletist-core/src/model.rs, lines 50 to 65&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// Everything that changes application state. Views push these; `App::apply`
/// applies them after the frame is drawn.
#[derive(Debug)]
pub enum Action {
    /// Cmd/Ctrl+O and the Connections button: show the saved connections,
    /// in the picker tab there is, or in a new one at the end.
    ShowConnections,
    CloseConnTab(ConnTabId),
    ActivateConnTab(ConnTabId),
    /// Cmd/Ctrl+1..9: activate the open connection at this position, as the
    /// header numbers them, if there is one.
    ActivateConnection(usize),
    /// Ctrl+Tab (+1) and Ctrl+Shift+Tab (-1), wrapping around.
    CycleConnTab(isize),
    /// A result from the backend.
    Backend(Event),
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are nearly 300 of them. The app applies them
until none are left, since one may queue more:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/app.rs#L967-L979&quot;&gt;src/app.rs, lines 967 to 979&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    /// Applies queued actions until none are left (an action may queue more).
    pub fn apply_actions(&amp;amp;mut self) {
        while !self.actions.is_empty() {
            for action in std::mem::take(&amp;amp;mut self.actions) {
                self.apply(action);
            }
        }
        self.read_reopened();
        self.format_rows();
        self.make_reviews();
        // Restart when done goes ahead in the frame the work ended in.
        self.tick_restart();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A frame starts by taking what the backend finished and applying it:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/app.rs#L8894-L8899&quot;&gt;src/app.rs, lines 8894 to 8899&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;    pub fn frame_ui(&amp;amp;mut self, ui: &amp;amp;mut egui::Ui) {
        self.focused = ui.ctx().input(|input| input.focused);
        self.note_use(ui.ctx());
        self.poll_backend();
        self.apply_actions();
        self.tick_lookups(ui.ctx());
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and ends by drawing the views, painting the one focus ring over
everything, and applying what the views asked for:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/src/app.rs#L8933-L8937&quot;&gt;src/app.rs, lines 8933 to 8937&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;        crate::ui::show(self, ui);
        // Over everything drawn: the ring of what has the keyboard.
        crate::ui::focus::paint(ui.ctx(), &amp;amp;self.look, &amp;amp;self.palette);
        crate::ui::keys::after_frame(ui.ctx());
        self.apply_actions();
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A view gets to change two things directly: the text a field is editing,
and the cursor position that field reports. Everything else waits for
&lt;code&gt;apply&lt;/code&gt;. This is what makes the tests above possible. A test can push an
&lt;code&gt;Action&lt;/code&gt; and check the state, with no drawing at all, or click and check
the same state.&lt;/p&gt;

&lt;p&gt;Database, network and disk work never runs on the UI thread:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/backend.rs#L1-L2&quot;&gt;crates/tabletist-core/src/backend.rs, lines 1 to 2&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;//! The backend: a tokio runtime on its own thread. The UI sends commands and
//! polls events each frame; the backend wakes the UI when an event is ready.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The database layer, &lt;code&gt;crates/tabletist-db&lt;/code&gt;, has no UI dependency at all.
It is tokio, the drivers (tokio-postgres, mysql_async, rusqlite, and
gcp-bigquery-client for BigQuery’s REST API), russh for SSH tunnels, and
sqlparser.&lt;/p&gt;

&lt;h2 id=&quot;an-mcp-server-that-cannot-leak-a-password&quot;&gt;An MCP server that cannot leak a password&lt;/h2&gt;

&lt;p&gt;Tabletist can let a coding agent, such as Claude Code or Cursor, read the
databases you allow, over the Model Context Protocol. An agent has three
tools: list the connections, describe a schema, run a query.&lt;/p&gt;

&lt;p&gt;What I wanted from it: an agent never sees where a database is or what
opens it. Not the host, not the password, not the SSH key. The crate that
speaks MCP, &lt;code&gt;crates/tabletist-mcp&lt;/code&gt;, cannot name any of that. It gets a
&lt;code&gt;Gateway&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-mcp/src/gateway.rs#L61-L86&quot;&gt;crates/tabletist-mcp/src/gateway.rs, lines 61 to 86&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// Whoever holds the connections agents may use.
///
/// A connection whose access is Off is not among [`Gateway::connections`]
/// and cannot be opened: to the server it does not exist.
pub trait Gateway: Send + Sync + &apos;static {
    type Session: Session;

    /// The connections agents may use, as they are now.
    fn connections(&amp;amp;self) -&amp;gt; Vec&amp;lt;Listed&amp;gt;;

    /// The session of the connection with this id, for one call. A
    /// connection runs one call at a time: a second one waits here, and is
    /// [`Failure::Busy`] when it has waited the connection&apos;s timeout.
    /// Opening is the implementation&apos;s to bound as well: the server&apos;s own
    /// timer starts when it has the session.
    ///
    /// Once `stop` is cancelled, whatever the session is doing is ended,
    /// and the call that asked answers [`tabletist_db::Error::Cancelled`].
    /// A statement that was sent is awaited to its end all the same: the
    /// futures of a session are never dropped half way.
    fn open(
        &amp;amp;self,
        id: &amp;amp;str,
        stop: &amp;amp;CancellationToken,
    ) -&amp;gt; impl Future&amp;lt;Output = Result&amp;lt;Self::Session, Failure&amp;gt;&amp;gt; + Send;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The app implements the gateway. The MCP crate sees connection ids and
names, and a &lt;code&gt;Session&lt;/code&gt; it can ask for schemas and reads. It has no type
that holds a host or a password, and the &lt;code&gt;secrets.rs&lt;/code&gt; test above makes
sure it never starts naming one.&lt;/p&gt;

&lt;p&gt;Every read is fenced twice. First a check on the text of the
statement, before anything reaches a database. Then the database itself:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-db/src/agent.rs#L14-L19&quot;&gt;crates/tabletist-db/src/agent.rs, lines 14 to 19&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;//! The check is the first fence, not the only one. What passes it runs
//! through [`crate::Connection::run_agent_read`], as any read-only script
//! does ([`crate::ScriptMode::ReadOnly`]): prepared alone by the database,
//! in a read-only transaction that is rolled back. A write this check took
//! for a read is refused there. [`Limits`] is how much a read may take,
//! and [`Answer`] what it gave.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;On PostgreSQL that means:&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-db/src/pg/script.rs#L446-L463&quot;&gt;crates/tabletist-db/src/pg/script.rs, lines 446 to 463&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// The open&apos;s steps, in order: the transaction, how it plans a cursor,
/// and for an agent&apos;s run its timeout and the views&apos; question (a script&apos;s
/// run takes the snapshot with `SELECT 1`), and last the guard&apos;s savepoint.
fn opening_steps(sent: Option&amp;lt;Sent&amp;lt;&apos;_&amp;gt;&amp;gt;) -&amp;gt; Vec&amp;lt;String&amp;gt; {
    let mut steps = vec![
        &quot;BEGIN READ ONLY&quot;.to_owned(),
        &quot;SET LOCAL cursor_tuple_fraction = 1&quot;.to_owned(),
    ];
    match sent {
        Some(sent) =&amp;gt; steps.extend([
            format!(&quot;SET LOCAL statement_timeout = {}&quot;, sent.timeout_ms()),
            super::views::reaching(),
        ]),
        None =&amp;gt; steps.push(&quot;SELECT 1&quot;.to_owned()),
    }
    steps.push(&quot;SAVEPOINT tabletist_guard&quot;.to_owned());
    steps
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;MySQL starts &lt;code&gt;START TRANSACTION READ ONLY&lt;/code&gt;, and SQLite runs under
&lt;code&gt;query_only&lt;/code&gt; with an authorizer. That authorizer is the one from the
&lt;code&gt;unsafe&lt;/code&gt; section: it is half of why &lt;code&gt;tabletist-sqlite-ffi&lt;/code&gt; exists.&lt;/p&gt;

&lt;p&gt;BigQuery is the exception, and I would rather say so. It has no
transactions, so there is no read-only one to fall back on. A BigQuery
connection is read-only in the whole app, and its adapter sends only a
statement the first check proves is a read. On BigQuery that check is the
fence that holds.&lt;/p&gt;

&lt;p&gt;What an agent sends (a statement, a value, a name) goes into a log of
calls the user can read in the app, and nowhere else. Not into the app’s
own log file, and not into an error sent back over the protocol. That took
more than care in my own code: the MCP SDK, sqlparser and tokio-postgres write what a
client sent to the logs themselves, so the app’s log keeps none of their
words. If &lt;code&gt;RUST_LOG&lt;/code&gt; lets such a line through, it says only that the line
was there. The other test in &lt;code&gt;secrets.rs&lt;/code&gt; runs a server against databases
it cannot open, sends a statement and a client name with markers in them,
and checks three things: no path reaches the agent or either log, the
markers are in the log of calls, and none of them is in a line the app
wrote.&lt;/p&gt;

&lt;p&gt;There is more to say about this part, and a later post will cover it.&lt;/p&gt;

&lt;h2 id=&quot;what-id-do-differently-and-whats-next&quot;&gt;What I’d do differently, and what’s next&lt;/h2&gt;

&lt;p&gt;The rules I trust are the ones a machine checks. Two of mine still are
not, and I would fix both before a fifth engine comes in.&lt;/p&gt;

&lt;p&gt;TextRole and focus should be tests, like &lt;code&gt;tests/keys.rs&lt;/code&gt;. Both rules hold
today because I review for them. A test that reads the views for a
&lt;code&gt;FontId&lt;/code&gt; or a &lt;code&gt;FontFamily&lt;/code&gt;, or for a ring painted round a control, would be
the same shape as the three tests above, and I would stop having to look.&lt;/p&gt;

&lt;p&gt;And &lt;code&gt;==&lt;/code&gt; on a &lt;code&gt;Driver&lt;/code&gt; should not compile at all. Today &lt;code&gt;Driver&lt;/code&gt; derives
&lt;code&gt;PartialEq&lt;/code&gt; because &lt;code&gt;ConnectSpec&lt;/code&gt;, the saved connection that holds it,
derives it too, and tests compare drivers with &lt;code&gt;assert_eq!&lt;/code&gt;. So the
engines rule leans on a test that reads text, where the type could have
said it. I would rather give up the derive, and write those comparisons
another way, than keep a rule the compiler could hold.&lt;/p&gt;

&lt;p&gt;What egui made hard, each with its scar in the code:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Paste on Hyprland.&lt;/strong&gt; winit made one Wayland data device per seat, and
egui-winit read the clipboard through it. Hyprland sends the selection
only to a client’s first data device, so paste never worked there. The
fix is in &lt;a href=&quot;https://github.com/crmne&quot;&gt;Carmine Paolino&lt;/a&gt;’s forks of winit
and egui. Tabletist shares them with
&lt;a href=&quot;https://github.com/crmne/spotifast&quot;&gt;spotifast&lt;/a&gt;, his Spotify client, along
with his &lt;a href=&quot;https://github.com/crmne/fastframe&quot;&gt;fastframe&lt;/a&gt; crates for text,
fonts, icons, themes and updates:&lt;/p&gt;

    &lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/Cargo.toml#L185-L192&quot;&gt;Cargo.toml, lines 185 to 192&lt;/a&gt;&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;language-toml&quot;&gt;# crmne/winit apps-0.30, used by the eframe fork above. It moves with egui:
# winit makes one wl_data_device per seat (for file drops), and egui-winit
# reads and writes the clipboard through it rather than through
# smithay-clipboard&apos;s own. Hyprland sends the selection only to a client&apos;s
# first data device, so with two of them paste never worked there (#115).
# The branch&apos;s tip: two macOS fixes past ed7caa90, the revision the egui
# fork and fastframe&apos;s guide name, which this one builds on.
winit = { git = &quot;https://github.com/crmne/winit&quot;, rev = &quot;0bed9dc0a7db02590a279fb8bac795fa39ee6948&quot; }
&lt;/code&gt;&lt;/pre&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Text a cell should not draw as is.&lt;/strong&gt; A database value can hold control
characters and invisible Unicode format characters. egui draws none of
them, and its bidi pass obeys the direction ones:&lt;/p&gt;

    &lt;p&gt;&lt;a href=&quot;https://github.com/igor-alexandrov/tabletist/blob/2294c3d1e8b65efedaa32b872720c4cea65a2cae/crates/tabletist-core/src/format.rs#L210-L214&quot;&gt;crates/tabletist-core/src/format.rs, lines 210 to 214&lt;/a&gt;&lt;/p&gt;

    &lt;pre&gt;&lt;code class=&quot;language-rust&quot;&gt;/// Whether `character` draws nothing, or changes how the text around it is
/// drawn: controls (C0, DEL and C1) and the invisible Unicode format
/// characters (general category Cf). egui draws none of these, and its bidi
/// pass obeys the direction ones, so U+202E shows the text after it
/// backwards.
&lt;/code&gt;&lt;/pre&gt;

    &lt;p&gt;In a database client that matters: U+202E can make a value read as
something it is not. Tabletist writes each of those characters out, as
&lt;code&gt;&amp;lt;U+202E&amp;gt;&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What it does not do yet: it speaks to these four engines and no others.
Binary values cannot be edited. Agents only read: they have no tool that
writes. The app is in English only.&lt;/p&gt;

&lt;p&gt;The code is at https://github.com/igor-alexandrov/tabletist, and the site
with downloads for all three systems is https://igor.works/tabletist/. If
something breaks, or a rule above has a hole I did not list, please file
an issue.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;I built Tabletist with a lot of help from Claude Code, and it helped me
check every code sample in this post against the repository. The words
and the decisions are mine.&lt;/em&gt;&lt;/p&gt;
</description>
        <pubDate>Wed, 18 Nov 2026 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/how-tabletist-is-built-a-native-database-client-in-rust-and-egui</link>
        <guid isPermaLink="true">https://igor.works/blog/how-tabletist-is-built-a-native-database-client-in-rust-and-egui</guid>
        
        <category>Rust</category>
        
        <category>Tabletist</category>
        
        
      </item>
    
      <item>
        <title>Docker Captain of the Year 🐳</title>
        <description>&lt;p&gt;I’m thrilled and honored to share that I’ve been recognized by &lt;a href=&quot;https://www.docker.com&quot;&gt;Docker&lt;/a&gt; as Docker Captain of the Year!&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;This came as a complete surprise. I had no idea I was even nominated, and being selected is beyond anything I could have imagined.&lt;/p&gt;

&lt;figure class=&quot;not-prose my-8 grid grid-cols-1 justify-items-center py-2&quot;&gt;
  &lt;img src=&quot;/assets/images/posts/2026-09-29/docker-captain-of-the-year.jpg&quot; alt=&quot;Igor Aleksandrov with the Docker Captain of the Year award&quot; style=&quot;max-width: 600px&quot; /&gt;

  
&lt;/figure&gt;

&lt;p&gt;I want to thank Docker and the amazing community. You are the reason I keep pushing forward, keep learning, and keep working to make our ecosystem better for everyone.&lt;/p&gt;

&lt;p&gt;This recognition belongs to all of us. Thank you!&lt;/p&gt;
</description>
        <pubDate>Tue, 29 Sep 2026 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/docker-captain-of-the-year</link>
        <guid isPermaLink="true">https://igor.works/blog/docker-captain-of-the-year</guid>
        
        <category>Docker</category>
        
        <category>Captain Speaks</category>
        
        
      </item>
    
      <item>
        <title>Where is the software development industry going?</title>
        <description>&lt;p&gt;What does the future of software development actually look like—and where does AI fit in?&lt;/p&gt;
</description>
        <pubDate>Tue, 21 Oct 2025 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/where-is-the-software-development-industry-going</link>
        <guid isPermaLink="true">https://igor.works/blog/where-is-the-software-development-industry-going</guid>
        
        
      </item>
    
      <item>
        <title>Kamal 2 – Get out of the cloud</title>
        <description>&lt;p&gt;I took the TropicalOnRails 2025 stage to challenge the status quo with the talk “Kamal 2 – Get Out of Cloud”. In this bold session, I explored the possibilities and implications of running your infrastructure without relying on traditional cloud providers. Drawing from real-world experience and practical experimentation, I unpacked the motivations behind adopting Kamal 2, the architectural decisions involved, and what this shift means for scalability, cost, and developer control. A compelling talk for anyone curious about modern deployment strategies beyond the cloud.&lt;/p&gt;
</description>
        <pubDate>Sat, 17 May 2025 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/kamal-2-get-out-of-the-cloud</link>
        <guid isPermaLink="true">https://igor.works/blog/kamal-2-get-out-of-the-cloud</guid>
        
        <category>Docker</category>
        
        <category>Rails</category>
        
        <category>DevOps</category>
        
        <category>Kamal</category>
        
        
      </item>
    
      <item>
        <title>Kamal cheat sheet</title>
        <description>&lt;p&gt;I use Kamal daily to deploy all the apps I maintain. I created a list of Kamal commands I use frequently. While this is not an exhaustive list, but it covers the most common tasks I usually perform.&lt;/p&gt;

&lt;!--more--&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
# The init command is used to create the config and secrets files once after Kamal is added to the app.
$ kamal init

# Install Docker on all target hosts
$ kamal server

# Aliases
# Kamal defines `kamal shell` out of the box, I usually add `kamal console` to quickly access the Rails console.
$ kamal shell [-d production]
# app exec -i --reuse &quot;bin/rails console&quot;
$ kamal console [-d production]

# Deploy app [to the staging environment]
$ kamal deploy [-d staging]

# Rollback app [to the VERSION] [in the staging environment]
$ kamal rollback [VERSION] [-d staging]

# Building images
# Most of the time you won&apos;t use the `kamal build` command directly,
# since it primarily used by `kamal deploy` and `kamal redeploy`.
# However, you can also use it to build the app image without pushing it, which is useful for testing.
$ kamal build dev

# Below are several commands to read the logs of the app and its accessories.
$ kamal app logs [--roles=web -n 100 -f]
$ kamal app logs [--primary -n 100 -f]
$ kamal app logs [--hosts=&amp;lt;ip_address&amp;gt; -n 100 -f]
$ kamal audit
# Show logs for the PgHero accessory [for the staging environment]
$ kamal accessory logs pghero [-d staging]
# Show logs for the proxy server [for the staging environment]
$ kamal proxy logs [-d staging]

# Show combined config (including secrets) [for the staging environment]. Can be useful to debug and in case you forgot your server ip-address.
$ kamal config [-d staging]

# Print secrets to stdout [for the staging environment]
$ kamal secrets print [-d staging]

# Show details about all containers grouped by role [for the staging environment]
$ kamal details [-d staging]

# Show details only about the app containers [for the staging environment], [for the web role]
$ kamal app details [-d staging] [--roles=web]

# Show details only about the PgHero accessory containers [for the staging environment]
$ kamal accessory details pghero -d staging
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To see all available commands, run &lt;code&gt;kamal help&lt;/code&gt;. If you prefer to save this cheat sheet as an image, &lt;a href=&quot;/assets/images/posts/2025-04-17/kamal-cheat-sheet.png&quot;&gt;use this link&lt;/a&gt;.&lt;/p&gt;
</description>
        <pubDate>Thu, 17 Apr 2025 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/kamal-cheat-sheet</link>
        <guid isPermaLink="true">https://igor.works/blog/kamal-cheat-sheet</guid>
        
        <category>Docker</category>
        
        <category>Rails</category>
        
        <category>DevOps</category>
        
        <category>Kamal</category>
        
        
      </item>
    
      <item>
        <title>Rails Dockerfile Best Practices – Part 1: Image Slimming</title>
        <description>&lt;p&gt;This article is a part of a series of posts where I will walk through every line of the Rails default &lt;code&gt;Dockerfile&lt;/code&gt; and explain the best practices and optimizations.&lt;/p&gt;

&lt;p&gt;Docker images can be optimized in different ways that include, but are not limited to, image size reduction, build performance optimization, security, and maintainability best practices, and application-specific optimizations. In the first article, I will touch only image size reduction optimization and explain why they are important.&lt;/p&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;why-to-optimize-the-image-size&quot;&gt;Why to optimize the image size?&lt;/h2&gt;

&lt;p&gt;As in every other process of software development, each developer will list his reasons why he wants to make his Docker builds faster. I will list the reasons that are most important to me.&lt;/p&gt;

&lt;h4 id=&quot;faster-builds--deployments&quot;&gt;Faster builds &amp;amp; deployments&lt;/h4&gt;

&lt;p&gt;Smaller images are faster to build because fewer files and layers need to be processed. This improves developer productivity, especially during iterative development cycles. Smaller images take less time to push to a registry and pull from it during deployments. This is especially critical in CI/CD pipelines where containers are built and deployed frequently.&lt;/p&gt;

&lt;h4 id=&quot;reduced-storage-costs--network-bandwidth-usage&quot;&gt;Reduced storage costs &amp;amp; network bandwidth usage&lt;/h4&gt;

&lt;p&gt;Smaller images consume less storage on container registries, local development machines, and production servers. This reduces infrastructure costs, especially for large-scale deployments. Smaller images use less bandwidth when transferred between servers, especially important when you’re building images locally or in CI/CD pipelines and pushing them to a registry.&lt;/p&gt;

&lt;figure&gt;
  &lt;blockquote&gt;We spent $3.2m on cloud in 2022... We stand to save about $7m in server expenses over five years from our cloud exit.&lt;/blockquote&gt;

  &lt;figcaption&gt;
    David Heinemeier Hansson —
    &lt;cite&gt;
      &lt;a href=&quot;https://world.hey.com/dhh/we-stand-to-save-7m-over-five-years-from-our-cloud-exit-53996caa&quot;&gt; HEY World &lt;/a&gt;
    &lt;/cite&gt;
  &lt;/figcaption&gt;
&lt;/figure&gt;

&lt;h4 id=&quot;improved-performance--security&quot;&gt;Improved performance &amp;amp; security&lt;/h4&gt;

&lt;p&gt;Smaller images require fewer resources (e.g., CPU, RAM) to load and run, improving the overall performance of containerized applications. Faster startup times mean your services are ready more quickly, which is crucial for scaling and high-availability systems. Minimal base images like &lt;code&gt;alpine&lt;/code&gt; or &lt;code&gt;debian-slim&lt;/code&gt; contain fewer pre-installed packages, decreasing the risk of unpatched or unnecessary software being exploited.&lt;/p&gt;

&lt;p&gt;Besides everything mentioned above, removing unnecessary files and tools minimizes distractions when diagnosing issues and leads to better maintainability and reduced technical debt.&lt;/p&gt;

&lt;h2 id=&quot;inspecting-docker-images&quot;&gt;Inspecting Docker images&lt;/h2&gt;

&lt;p&gt;To get different parameters of the image, including the  the size, you can either look at the Docker Desktop or run the &lt;code&gt;docker images&lt;/code&gt; command in the terminal.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker images
REPOSITORY        TAG       IMAGE ID       CREATED        SIZE
kamal-dashboard   latest    673737b771cd   2 days ago     619MB
kamal-proxy       latest    5f6cd8983746   6 weeks ago    115MB
docs-server       latest    a810244e3d88   6 weeks ago    1.18GB
busybox           latest    63cd0d5fb10d   3 months ago   4.04MB
postgres          latest    6c9aa6ecd71d   3 months ago   456MB
postgres          16.4      ced3ad69d60c   3 months ago   453MB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Knowing the size of the image does not give you the full picture. You don’t know what is inside the image, how many layers it has, or how big each layer is. A &lt;strong&gt;Docker image layer&lt;/strong&gt; is a read-only, &lt;strong&gt;immutable file system layer&lt;/strong&gt; that is a component of a Docker image. Each layer represents a set of changes made to the image’s file system, such as adding files, modifying configurations, or installing software.&lt;/p&gt;

&lt;p&gt;Docker images are built incrementally, layer by layer, and each layer corresponds to an instruction in the &lt;code&gt;Dockerfile&lt;/code&gt;. To get the layers of the image, you can run the &lt;code&gt;docker history&lt;/code&gt; command.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker history kamal-dashboard:latest
IMAGE          CREATED       CREATED BY                                      SIZE      COMMENT
673737b771cd   4 days ago    CMD [&quot;./bin/thrust&quot; &quot;./bin/rails&quot; &quot;server&quot;]     0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    EXPOSE map[80/tcp:{}]                           0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    ENTRYPOINT [&quot;/rails/bin/docker-entrypoint&quot;]     0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    USER 1000:1000                                  0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    RUN /bin/sh -c groupadd --system --gid 1000 …   54MB      buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    COPY /rails /rails # buildkit                   56.2MB    buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    COPY /usr/local/bundle /usr/local/bundle # b…   153MB     buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    ENV RAILS_ENV=production BUNDLE_DEPLOYMENT=1…   0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    RUN /bin/sh -c apt-get update -qq &amp;amp;&amp;amp;     apt…   137MB     buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      4 days ago    WORKDIR /rails                                  0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   CMD [&quot;irb&quot;]                                     0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   RUN /bin/sh -c set -eux;  mkdir &quot;$GEM_HOME&quot;;…   0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV PATH=/usr/local/bundle/bin:/usr/local/sb…   0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV BUNDLE_SILENCE_ROOT_WARNING=1 BUNDLE_APP…   0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV GEM_HOME=/usr/local/bundle                  0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   RUN /bin/sh -c set -eux;   savedAptMark=&quot;$(a…   78.1MB    buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV RUBY_DOWNLOAD_SHA256=018d59ffb52be3c0a6d…   0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV RUBY_DOWNLOAD_URL=https://cache.ruby-lan…   0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV RUBY_VERSION=3.4.1                          0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   ENV LANG=C.UTF-8                                0B        buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   RUN /bin/sh -c set -eux;  mkdir -p /usr/loca…   19B       buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   RUN /bin/sh -c set -eux;  apt-get update;  a…   43.9MB    buildkit.dockerfile.v0
&amp;lt;missing&amp;gt;      3 weeks ago   # debian.sh --arch &apos;arm64&apos; out/ &apos;bookworm&apos; &apos;…   97.2MB    debuerreotype 0.15
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Since I already provided theory about images, and layers, it is time to explore the &lt;code&gt;Dockerfile&lt;/code&gt;. Starting from Rails 7.1, the &lt;code&gt;Dockerfile&lt;/code&gt; is generated with the new Rails application. Below is an example of what it may look like.&lt;/p&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
# syntax=docker/dockerfile:1
# check=error=true

# Make sure RUBY_VERSION matches the Ruby version in .ruby-version
ARG RUBY_VERSION=3.4.1
FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base

# Rails app lives here
WORKDIR /rails

# Install base packages
# Replace libpq-dev with sqlite3 if using SQLite, or libmysqlclient-dev if using MySQL
RUN apt-get update -qq &amp;amp;&amp;amp; \
    apt-get install --no-install-recommends -y curl libjemalloc2 libvips libpq-dev &amp;amp;&amp;amp; \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# Set production environment
ENV RAILS_ENV=&quot;production&quot; \
    BUNDLE_DEPLOYMENT=&quot;1&quot; \
    BUNDLE_PATH=&quot;/usr/local/bundle&quot; \
    BUNDLE_WITHOUT=&quot;development&quot;

# Throw-away build stage to reduce size of final image
FROM base AS build

# Install packages needed to build gems
RUN apt-get update -qq &amp;amp;&amp;amp; \
    apt-get install --no-install-recommends -y build-essential curl git pkg-config libyaml-dev &amp;amp;&amp;amp; \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives

# Install application gems
COPY Gemfile Gemfile.lock ./
RUN bundle install &amp;amp;&amp;amp; \
    rm -rf ~/.bundle/ &quot;${BUNDLE_PATH}&quot;/ruby/*/cache &quot;${BUNDLE_PATH}&quot;/ruby/*/bundler/gems/*/.git &amp;amp;&amp;amp; \
    bundle exec bootsnap precompile --gemfile

# Copy application code
COPY . .

# Precompile bootsnap code for faster boot times
RUN bundle exec bootsnap precompile app/ lib/

# Precompiling assets for production without requiring secret RAILS_MASTER_KEY
RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile

# Final stage for app image
FROM base

# Copy built artifacts: gems, application
COPY --from=build &quot;${BUNDLE_PATH}&quot; &quot;${BUNDLE_PATH}&quot;
COPY --from=build /rails /rails

# Run and own only the runtime files as a non-root user for security
RUN groupadd --system --gid 1000 rails &amp;amp;&amp;amp; \
    useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash &amp;amp;&amp;amp; \
    chown -R rails:rails db log storage tmp
USER 1000:1000

# Entrypoint prepares the database.
ENTRYPOINT [&quot;/rails/bin/docker-entrypoint&quot;]

# Start server via Thruster by default, this can be overwritten at runtime
EXPOSE 80
CMD [&quot;./bin/thrust&quot;, &quot;./bin/rails&quot;, &quot;server&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Below I will provide a list of approaches and rules that where applied to the &lt;code&gt;Dockerfile&lt;/code&gt; above to make the final image size efficient.&lt;/p&gt;

&lt;h2 id=&quot;optimize-packages-installations&quot;&gt;Optimize packages installations&lt;/h2&gt;

&lt;p&gt;I am sure you keep only needed software on your local development machine. The same should be applied to Docker images. In the examples below I will consistently making worse &lt;a href=&quot;/assets/files/posts/2025-01-28/original.dockerfile&quot;&gt;the Dockerfile extracted&lt;/a&gt; from the Rails Dockerfile above. I will reference it as an &lt;strong&gt;original&lt;/strong&gt; &lt;code&gt;Dockerfile&lt;/code&gt; version.&lt;/p&gt;

&lt;h3 id=&quot;rule-1-use-minimal-base-images&quot;&gt;Rule #1: Use minimal base images&lt;/h3&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The base image is the starting point for the &lt;code&gt;Dockerfile&lt;/code&gt;. It is the image that is used to create the container. The base image is the first layer in the &lt;code&gt;Dockerfile&lt;/code&gt;, and it is the only layer that is not created by the &lt;code&gt;Dockerfile&lt;/code&gt; itself.&lt;/p&gt;

&lt;p&gt;The base image is specified with the &lt;code&gt;FROM&lt;/code&gt; command, followed by the image name and tag. The tag is optional, and if not specified, the &lt;code&gt;latest&lt;/code&gt; tag is used. The base image can be any image available on Docker Hub or any other registry.&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;Dockerfile&lt;/code&gt; about, we are using the &lt;code&gt;ruby&lt;/code&gt; image with the &lt;code&gt;3.4.1-slim&lt;/code&gt; tag. The &lt;code&gt;ruby&lt;/code&gt; image is &lt;a href=&quot;https://hub.docker.com/_/ruby&quot;&gt;the official Ruby image&lt;/a&gt; available on Docker Hub. The &lt;code&gt;3.4.1-slim&lt;/code&gt; tag is a slim version of the Ruby image that is based on the &lt;code&gt;debian-slim&lt;/code&gt; image. While the &lt;code&gt;debian-slim&lt;/code&gt; image is a minimal version of the Debian Linux image that is optimized for size. Look at the table below to get an idea of how smaller the &lt;code&gt;slim&lt;/code&gt; image is.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker images --filter &quot;reference=ruby&quot;
REPOSITORY   TAG              IMAGE ID       CREATED      SIZE
ruby         3.4.1-slim       0bf957e453fd   5 days ago   219MB
ruby         3.4.1-alpine     cf9b1b8d4a0c   5 days ago   99.1MB
ruby         3.4.1-bookworm   1e77081540c0   5 days ago   1.01GB
&lt;/code&gt;&lt;/pre&gt;

&lt;figure&gt;
  &lt;figcaption&gt;Debian Releases&lt;/figcaption&gt;

  &lt;em&gt;
    As of January, 2024, current Debian release is called &lt;strong&gt;bookworm&lt;/strong&gt; and the previous one is &lt;strong&gt;bullseye&lt;/strong&gt;.
  &lt;/em&gt;
&lt;/figure&gt;

&lt;p&gt;219 MB instead of 1GB — a huge difference. But what if the &lt;code&gt;alpine&lt;/code&gt; image is even smaller? The &lt;code&gt;alpine&lt;/code&gt; image is based on the Alpine Linux distribution, which is a super lightweight Linux distribution that is optimized for size and security. Alpine uses the &lt;code&gt;musl&lt;/code&gt; library (instead of &lt;code&gt;glibc&lt;/code&gt;) and &lt;code&gt;busybox&lt;/code&gt; (a compact set of Unix utilities) instead of GNU counterparts. While it is technically possible to use the &lt;code&gt;alpine&lt;/code&gt; image to run Rails, I will not cover it in this article.&lt;/p&gt;

&lt;h3 id=&quot;rule-2-minimize-layers&quot;&gt;Rule #2: Minimize layers&lt;/h3&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
RUN apt-get update -qq &amp;amp;&amp;amp; \
    apt-get install --no-install-recommends -y curl libjemalloc2 libvips libpq-dev &amp;amp;&amp;amp; \
    rm -rf /var/lib/apt/lists /var/cache/apt/archives
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each &lt;code&gt;RUN&lt;/code&gt;, &lt;code&gt;COPY&lt;/code&gt; and &lt;code&gt;FROM&lt;/code&gt; instruction in &lt;code&gt;Dockerfile&lt;/code&gt; creates a new layer. The more layers you have, the bigger the image size. This is why the best practice is to combine multiple commands into a single &lt;code&gt;RUN&lt;/code&gt; instruction. To illustrate this point, let’s look at the example below.&lt;/p&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
# syntax=docker/dockerfile:1
# check=error=true

# Make sure RUBY_VERSION matches the Ruby version in .ruby-version
ARG RUBY_VERSION=3.4.1
FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base

RUN apt-get update -qq
RUN apt-get install --no-install-recommends -y curl
RUN apt-get install --no-install-recommends -y libjemalloc2
RUN apt-get install --no-install-recommends -y libvips
RUN apt-get install --no-install-recommends -y libpq-dev
RUN rm -rf /var/lib/apt/lists /var/cache/apt/archives

CMD [&quot;echo&quot;, &quot;Whalecome!&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have split the &lt;code&gt;RUN&lt;/code&gt; instruction into multiple lines, which obviously makes them more &lt;a href=&quot;/assets/files/posts/2025-01-28/no-minimize-layers.dockerfile&quot;&gt;human-readable&lt;/a&gt;. But how will it affect the size of the image? Let’s build the image and check it out.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ time docker build -t no-minimize-layers --no-cache -f no-minimize-layers.dockerfile .
0.31s user 0.28s system 2% cpu 28.577 total
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It took 28 seconds to build the image, while to build the &lt;a href=&quot;/assets/files/posts/2025-01-28/original.dockerfile&quot;&gt;original version with minimized layers&lt;/a&gt; takes only 19 seconds (&lt;strong&gt;almost 33% faster&lt;/strong&gt;).&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ time docker build -t original --no-cache -f original.dockerfile .
0.25s user 0.28s system 2% cpu 19.909 total
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s check the size of the images.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker images --filter &quot;reference=*original*&quot; --filter &quot;reference=*no-minimize*&quot;
REPOSITORY           TAG       IMAGE ID       CREATED          SIZE
original             latest    f1363df79c8a   8 seconds ago    356MB
no-minimize-layers   latest    ad3945c8a8ee   43 seconds ago   379MB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The image with minimized layers is 23 MB smaller than the one with no minimized layers. This is a &lt;strong&gt;6% reduction in size&lt;/strong&gt;. While it seems like a small difference in this example, the difference will be much bigger if you split all the &lt;code&gt;RUN&lt;/code&gt; instructions into multiple lines.&lt;/p&gt;

&lt;h3 id=&quot;rule-3-install-only-what-needed&quot;&gt;Rule #3: Install only what needed&lt;/h3&gt;

&lt;p&gt;By default, &lt;code&gt;apt-get install&lt;/code&gt; installs the recommended packages as well as packages you asked it to install. The &lt;code&gt;--no-install-recommends&lt;/code&gt; option tells &lt;code&gt;apt-get&lt;/code&gt; to install only the packages that are explicitly specified and not the recommended ones.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ time docker build -t without-no-install-recommends --no-cache -f without-no-install-recommends.dockerfile .
0.33s user 0.30s system 2% cpu 29.786 total
&lt;/code&gt;&lt;/pre&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker images --filter &quot;reference=*original*&quot; --filter &quot;reference=*recommends*&quot;
REPOSITORY                      TAG       IMAGE ID       CREATED          SIZE
without-no-install-recommends   latest    41e6e37f1e2b   3 minutes ago    426MB
minimize-layers                 latest    dff22c85d84c   17 minutes ago   356MB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the image without &lt;code&gt;--no-install-recommends&lt;/code&gt; is 70 MB bigger than the &lt;a href=&quot;/assets/files/posts/2025-01-28/original.dockerfile&quot;&gt;original one&lt;/a&gt;. This is a &lt;strong&gt;16% increase in size&lt;/strong&gt;.&lt;/p&gt;

&lt;figure&gt;
  &lt;figcaption&gt;What files where added?&lt;/figcaption&gt;

  &lt;em&gt;
    Use &lt;code&gt;dive&lt;/code&gt; utility to see which files were added to the image – read more about it in the end of the article.
  &lt;/em&gt;
&lt;/figure&gt;

&lt;h3 id=&quot;rule-4-clean-up-after-installations&quot;&gt;Rule #4: Clean up after installations&lt;/h3&gt;

&lt;p&gt;The original &lt;code&gt;Dockerfile&lt;/code&gt; includes the &lt;code&gt;rm -rf /var/lib/apt/lists/* /var/cache/apt/archives&lt;/code&gt; command after the &lt;code&gt;apt-get install&lt;/code&gt; command. This command removes the package lists and archives that are no longer needed after the installation. Let’s see how it affects the image size, to achieve that, I will create a new &lt;code&gt;Dockerfile&lt;/code&gt; &lt;a href=&quot;/assets/files/posts/2025-01-28/without-cleaning.dockerfile&quot;&gt;without the cleaning command&lt;/a&gt;.&lt;/p&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
RUN apt-get update -qq &amp;amp;&amp;amp; \
    apt-get install --no-install-recommends -y curl libjemalloc2 libvips libpq-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Building the images takes almost the same time as the original one, which makes sense.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ time docker build -t without-cleaning --no-cache -f without-cleaning.dockerfile .
0.28s user 0.30s system 2% cpu 21.658 total
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s check the size of the images.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker images --filter &quot;reference=*original*&quot; --filter &quot;reference=*cleaning*&quot;
REPOSITORY         TAG       IMAGE ID       CREATED          SIZE
without-cleaning   latest    52884fe50773   2 minutes ago    375MB
original           latest    f1363df79c8a   16 minutes ago   356MB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The image without cleaning is 19 MB bigger than the one with cleaning, this is a &lt;strong&gt;5% increase in size&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;the-worst-scenario&quot;&gt;The worst scenario&lt;/h3&gt;

&lt;p&gt;What if all four optimizations mentioned above are not applied? Let’s create a new &lt;code&gt;Dockerfile&lt;/code&gt; &lt;a href=&quot;/assets/files/posts/2025-01-28/without-optimizations.dockerfile&quot;&gt;without any optimizations&lt;/a&gt; and build the image.&lt;/p&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
# syntax=docker/dockerfile:1
# check=error=true

ARG RUBY_VERSION=3.4.1
FROM docker.io/library/ruby:$RUBY_VERSION AS base

RUN apt-get update -qq
RUN apt-get install -y curl
RUN apt-get install -y libjemalloc2
RUN apt-get install -y libvips
RUN apt-get install -y libpq-dev

CMD [&quot;echo&quot;, &quot;Whalecome!&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ time docker build -t without-optimizations --no-cache -f without-optimizations.dockerfile .
0.46s user 0.45s system 1% cpu 1:02.21 total
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Wow, it took more than a minute to build the image.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜ docker images --filter &quot;reference=*original*&quot; --filter &quot;reference=*without-optimizations*&quot;
REPOSITORY              TAG       IMAGE ID       CREATED         SIZE
without-optimizations   latest    45671929c8e4   2 minutes ago   1.07GB
original                latest    f1363df79c8a   27 hours ago    356MB
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The image without optimizations is 714 MB bigger than the original one, this is a &lt;strong&gt;200% increase in size&lt;/strong&gt;. This clearly shows how important it is to optimize the &lt;code&gt;Dockerfile&lt;/code&gt;, larger images take more time to build and consume more disk space.&lt;/p&gt;

&lt;h2 id=&quot;always-use-dockerignore&quot;&gt;Always use .dockerignore&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;.dockerignore&lt;/code&gt; file is similar to the &lt;code&gt;.gitignore&lt;/code&gt; file used by Git. It is used to exclude files and directories from the context of the build. The context is the set of files and directories that are sent to the Docker daemon when building an image. The context is sent to the Docker daemon as a tarball, so it is important to keep it as small as possible.&lt;/p&gt;

&lt;p&gt;If, for any reason, you don’t have the &lt;code&gt;.dockerignore&lt;/code&gt; file in your project, you can create it manually. I suggest you use the official Rails &lt;code&gt;.dockerignore&lt;/code&gt; &lt;a href=&quot;https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/app/templates/dockerignore.tt&quot;&gt;file template&lt;/a&gt; as a starting point. Below is an example of what it may look like.&lt;/p&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files.

# Ignore git directory.
/.git/
/.gitignore

# Ignore bundler config.
/.bundle

# Ignore all environment files.
/.env*

# Ignore all default key files.
/config/master.key
/config/credentials/*.key

# Ignore all logfiles and tempfiles.
/log/*
/tmp/*
!/log/.keep
!/tmp/.keep

# Ignore pidfiles, but keep the directory.
/tmp/pids/*
!/tmp/pids/.keep

# Ignore storage (uploaded files in development and any SQLite databases).
/storage/*
!/storage/.keep
/tmp/storage/*
!/tmp/storage/.keep

# Ignore assets.
/node_modules/
/app/assets/builds/*
!/app/assets/builds/.keep
/public/assets

# Ignore CI service files.
/.github

# Ignore development files
/.devcontainer

# Ignore Docker-related files
/.dockerignore
/Dockerfile*
&lt;/code&gt;&lt;/pre&gt;

&lt;figure&gt;
  &lt;figcaption&gt;Improving security&lt;/figcaption&gt;

  &lt;em&gt;
    Having a &lt;code&gt;.dockerfile&lt;/code&gt; file in the project not only allows excluding unnecessary files and directories (e.g., GitHub workflows from the &lt;code&gt;.github&lt;/code&gt; folder or JavaScript dependencies from the &lt;code&gt;node_modules&lt;/code&gt;) from the context. It also helps to avoid accidentally adding sensitive information to the image. For example, the &lt;code&gt;.env&lt;/code&gt; file that contains the environment variables or the &lt;code&gt;master.key&lt;/code&gt; file that is used to decrypt the credentials.

  &lt;/em&gt;
&lt;/figure&gt;

&lt;h2 id=&quot;use-dive&quot;&gt;Use Dive&lt;/h2&gt;

&lt;p&gt;All the optimizations mentioned above may seem obvious when explained. What to do if you already have a massive image, and you don’t know where to start?&lt;/p&gt;

&lt;p&gt;My favorite and most useful tool is &lt;a href=&quot;https://github.com/wagoodman/dive&quot;&gt;Dive&lt;/a&gt;. Dive is a TUI tool for exploring a Docker image, layer contents, and discovering ways to shrink the image size. Dive can be installed with your system package manager, or you can use its official Docker image to run it. Let’s use the image from our worst scenario.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest without-optimizations
&lt;/code&gt;&lt;/pre&gt;

&lt;figure class=&quot;not-prose my-8 grid grid-cols-1 justify-items-center py-2&quot;&gt;
  &lt;img src=&quot;/assets/images/posts/2025-01-28/dive.png&quot; alt=&quot;Dive Docker layers inspect tool&quot; style=&quot;max-width: 100%&quot; /&gt;

  
  &lt;figcaption class=&quot;mt-2 block text-center text-sm text-gray-600&quot;&gt;
    Dive Docker layers inspect tool
  &lt;/figcaption&gt;
  
&lt;/figure&gt;

&lt;p&gt;In the screenshot above, you can see the inspection of our the most non-optimal image. Dive shows the size of each layer, the total size of the image, and the files that were changed (added, modified, or deleted) in each layer. For me, this is the most useful feature of Dive. By listing the files in the right panel, you can easily identify the files that are not needed and remove commands that add them to the image.&lt;/p&gt;

&lt;p&gt;One thing that I truly love about Dive is that, besides having a terminal UI, it also can provide a CI-friendly output, which can be effective in a local development too. To use it, run Dive with the &lt;code&gt;CI&lt;/code&gt; environment variable set to &lt;code&gt;true&lt;/code&gt;, the output of the command is in the screenshot below.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
docker run -e CI=true --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest without-optimizations
&lt;/code&gt;&lt;/pre&gt;

&lt;figure class=&quot;not-prose my-8 grid grid-cols-1 justify-items-center py-2&quot;&gt;
  &lt;img src=&quot;/assets/images/posts/2025-01-28/dive-ci.png&quot; alt=&quot;Dive CI-friendly output&quot; style=&quot;max-width: 100%&quot; /&gt;

  
  &lt;figcaption class=&quot;mt-2 block text-center text-sm text-gray-600&quot;&gt;
    Dive CI-friendly output
  &lt;/figcaption&gt;
  
&lt;/figure&gt;

&lt;p&gt;My personal preference is to use Dive on a scheduled basis, for example, once a week, to ensure your images are still in a good shape. In the upcoming articles, I will cover automated workflows I use to check my Dockerfile, including Dive and &lt;a href=&quot;https://github.com/hadolint/hadolint&quot;&gt;Hadolint&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;dont-squash-layers&quot;&gt;Don’t squash layers&lt;/h2&gt;

&lt;p&gt;One approach to minimizing image size that I’ve seen is to try to squash the layers. The idea was to combine several layers into a single layer to reduce the image size. Docker had an experimental option &lt;code&gt;--squash&lt;/code&gt;, besides this, there were third-party tools like &lt;a href=&quot;https://github.com/goldmann/docker-squash&quot;&gt;docker-squash&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;While this approach worked in the past, currently it is deprecated and not recommended to use. Squashing layers destroyed Docker’s fundamental feature of layer caching. Apart from that, while using &lt;code&gt;--squash&lt;/code&gt; you could unintentionally include sensitive or temporary files from earlier layers in the final image. This is an all-or-nothing approach that lacks fine-grained control.&lt;/p&gt;

&lt;p&gt;Instead of squashing layers, it is recommended to use multi-stage builds. Rails &lt;code&gt;Dockerfile&lt;/code&gt; already uses multi-stage builds, I will explain how it works in the next article.&lt;/p&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;Optimizing Docker images, just like any other optimization, &lt;strong&gt;cannot be done once and forgotten&lt;/strong&gt;. It is an ongoing process that requires regular checks and improvements. I tried to cover the basics, but they are critical to know and understand. In the next articles, I will cover more advanced techniques and tools that can help to make your Docker builds faster and more efficient.&lt;/p&gt;
</description>
        <pubDate>Tue, 28 Jan 2025 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/rails-dockerfile-best-practices-part-1-image-slimming</link>
        <guid isPermaLink="true">https://igor.works/blog/rails-dockerfile-best-practices-part-1-image-slimming</guid>
        
        <category>Docker</category>
        
        <category>Rails</category>
        
        <category>Captain Speaks</category>
        
        <category>DevOps</category>
        
        
      </item>
    
      <item>
        <title>Use Docker to template local database</title>
        <description>&lt;p&gt;How often do you reset your local development database? Depending on the task I am working on, I can do this even ten times a day. The reasons can be different. You or your teammate pushed an irreversible migration, which is of course not the best practice, but happens in the real life. Or you simply corrupted the data while implementing some new functionality.&lt;/p&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;tldr&quot;&gt;TL;DR&lt;/h2&gt;

&lt;p&gt;Resetting a local development database is a common task that can take a lot of time when the database dump is large. When you need to reset your local development database, you can use Docker to template it. This will save you a lot of time when your database dump is large.&lt;/p&gt;

&lt;p&gt;The repository with the scripts is available &lt;a href=&quot;https://github.com/igor-alexandrov/docker-db-template&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;the-problem&quot;&gt;The Problem&lt;/h2&gt;

&lt;p&gt;When your project DB size is 100Mb, it is not a problem to run &lt;code&gt;psql -d project_development &amp;lt; project_development.sql&lt;/code&gt; to restore the database. But what if your project database dump is 50 GB or 100 GB? This is a common size of the database for the project that does have some real clients.&lt;/p&gt;

&lt;p&gt;On my Mac M1 Pro, it usually takes about 30 minutes to restore a 50GB dump from the SQL data file. Resetting such a database two times a day can cost you your lunchtime. Sounds so-so.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜  backend git:(invoices) ✗ time psql -d safari_development_1 -f ~/Downloads/safari_development.sql

psql -d safari_development -f ~/Downloads/safari_development.sql  38.48s user 121.23s system 9% cpu 27:49.06 total
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Having the dump in the binary format will make it significantly smaller (8 GB instead of 50), but still, it will take a lot of time to restore it.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜  backend git:(master) time pg_restore -d safari_development ~/Downloads/safari_development.dump

pg_restore -d safari_development ~/Downloads/safari_development.dump  180.61s user 75.97s system 13% cpu 30:39.12 total
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;How to speed things up?&lt;/p&gt;

&lt;h2 id=&quot;general-idea&quot;&gt;General Idea&lt;/h2&gt;

&lt;p&gt;The general idea is elementary – &lt;strong&gt;somehow avoid restoring the database dump&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;A similar approach works in the database replication. When your master database goes down for whatever reason, you can immediately switch to the slave database, which will become the master. You don’t need to wait while you will restore the dump from the backup.&lt;/p&gt;

&lt;p&gt;How can we avoid restoring dump when working locally? The idea is to have a template of the database somewhere and simply copy this template instead of restoring the dump with &lt;code&gt;psql&lt;/code&gt; or &lt;code&gt;pg_restore&lt;/code&gt;.&lt;/p&gt;

&lt;figure&gt;
  &lt;figcaption&gt;PostgreSQL Templates&lt;/figcaption&gt;

  &lt;em&gt;
    PostgreSQL has a built-in &lt;a href=&quot;https://www.postgresql.org/docs/current/manage-ag-templatedbs.html&quot;&gt;template system&lt;/a&gt;. These templates allow users to replicate the structure, schema, and any data stored in them into newly created databases. By default, PostgreSQL provides two templates: &lt;code&gt;template0&lt;/code&gt; and &lt;code&gt;template1&lt;/code&gt;. This feature helps standardize new databases and streamline the creation process across multiple instances. However, since during the initialization of the database all the objects from the template are reinitialized again, it still takes quite a lot of time to run.
  &lt;/em&gt;

  &lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
    ➜  backend git:(master) time createdb -T safari_development_template safari_development
    createdb -T safari_development_template safari_development  0.00s user 0.01s system 0% cpu 17:34.90 total
  &lt;/code&gt;&lt;/pre&gt;
&lt;/figure&gt;

&lt;p&gt;What does it mean with PostgreSQL? This means we should have a full copy of our PostgreSQL cluster on the disk and copy it every time we want to “restore” the database. With PostgreSQL (or any else database except the SQLite) that is installed on directly your host machine, this can be a rather tricky task. You will have to worry about management of PostgreSQL config files, environment variables and tons of other stuff. Believe me, this won’t make you development efficient.&lt;/p&gt;

&lt;p&gt;This is where Docker comes in place. My idea was to have two versions of the database – the template and the current working version, and to have an ability to quickly copy the template to the current version.&lt;/p&gt;

&lt;h2 id=&quot;implementation&quot;&gt;Implementation&lt;/h2&gt;

&lt;p&gt;Before going into the detail, I want to quickly walk through the main Docker concepts that I used in this implementation. The first one is the Docker image. The image is a read-only blueprint with instructions for creating a Docker container. The second one is the Docker container. The container is a runnable instance of an image. Containers and images are managed with &lt;code&gt;docker container&lt;/code&gt; and &lt;code&gt;docker image&lt;/code&gt; &lt;a href=&quot;https://docs.docker.com/reference/cli/docker/container/&quot;&gt;commands&lt;/a&gt; &lt;a href=&quot;https://docs.docker.com/reference/cli/docker/image/&quot;&gt;accordingly&lt;/a&gt;. The third one is the Docker volume. The volume is a persistent data storage mechanism that allows data to exist beyond the lifecycle of a container.&lt;/p&gt;

&lt;figure&gt;
  &lt;figcaption&gt;Docker Volumes 101&lt;/figcaption&gt;

  &lt;em&gt;
    A key feature of a Docker container is its &lt;strong&gt;temporary nature&lt;/strong&gt;. When a container is deleted, any changes made to its file system are lost. To address this, Docker uses volumes. The concept is to store data on the host machine’s file system rather than within the container itself, ensuring it persists beyond the container’s lifecycle.
  &lt;/em&gt;
&lt;/figure&gt;

&lt;p&gt;Dealing with a Docker volume is straightforward. Once the volume is created, it can be attached to the container. When the container is deleted, the volume is still there. You can attach the volume to another container and continue working with the data. Volumes are managed with the &lt;code&gt;docker volume&lt;/code&gt; &lt;a href=&quot;https://docs.docker.com/reference/cli/docker/volume/&quot;&gt;command&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Lets take a look the small script below.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
#!/bin/bash

set -e

# Create a volume
docker volume create safari-development-template

# Start a container with the PostgreSQL database and attach the volume
docker run --name safari-development-template \
  -p 5432:5432 \
  -e POSTGRES_USER=igor \
  -e POSTGRES_DB=safari_development \
  -e POSTGRES_HOST_AUTH_METHOD=trust \
  -v safari-development-template:/var/lib/postgresql/data \
  -d postgres:17
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What does it do? It creates a volume with the name &lt;code&gt;safari-development-template&lt;/code&gt; and starts a container with the PostgreSQL database. The container is named &lt;code&gt;safari-development-template&lt;/code&gt; and exposes the port 5432. The database name is &lt;code&gt;safari_development&lt;/code&gt; and the user is &lt;code&gt;igor&lt;/code&gt;. The volume &lt;code&gt;safari-development-template&lt;/code&gt; is attached to the container.&lt;/p&gt;

&lt;p&gt;Once the container is up, I can restore the database dump into it.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
psql -d safari_development \
  -h localhost \
  -p 5432 &amp;lt; safari_development.sql
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;After about 30 minutes, the database has been restored. With &lt;a href=&quot;https://www.docker.com/products/docker-desktop/&quot;&gt;Docker Desktop&lt;/a&gt;, I can see the volume with its size.&lt;/p&gt;

&lt;figure class=&quot;not-prose my-8 grid grid-cols-1 justify-items-center py-2&quot;&gt;
  &lt;img src=&quot;/assets/images/posts/2024-10-27/docker-volumes-listing.png&quot; alt=&quot;Docker Volumes Listing&quot; style=&quot;max-width: 600px&quot; /&gt;

  
  &lt;figcaption class=&quot;mt-2 block text-center text-sm text-gray-600&quot;&gt;
    Docker Volumes Listing
  &lt;/figcaption&gt;
  
&lt;/figure&gt;

&lt;p&gt;The setup we have now is pretty standard. Our database is running in the container and the data is stored on the host machine. Such a setup allows us to do local development. Unfortunately, from the time perspective, it is not anyhow different the restoring the database dump directly on the host machine.&lt;/p&gt;

&lt;p&gt;Now let’s move to the interesting part. Firstly, we need to create another volume that will be used for the working database. This can be done similar to the template volume creation.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
docker volume create safari-development
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So now we have two volumes: &lt;code&gt;safari-development-template&lt;/code&gt; and &lt;code&gt;safari-development&lt;/code&gt;. The first one has the data and the second one is empty. The idea is to copy the data from the first volume to the second one. Docker doesn’t provide a direct way to copy the data between the volumes, but the data can be copied between the volumes that are attached to the container. With this idea in mind I decided to use the smallest possible Docker image that has the &lt;code&gt;cp&lt;/code&gt; command.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;busybox&lt;/code&gt; &lt;a href=&quot;https://hub.docker.com/_/busybox&quot;&gt;image&lt;/a&gt; is the best choice for this. It is only 4 MB in size and has many common UNIX utilities. To copy the data between the volumes, I  started a container with the &lt;code&gt;busybox&lt;/code&gt; image and attached both volumes to it to run the &lt;code&gt;cp&lt;/code&gt; command.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
docker container run --rm -it \
    -v safari-development-template:/from \
    -v safari-development:/to \
    busybox sh -c &quot;cd /from ; cp -av . /to&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;figure&gt;
  &lt;figcaption&gt;BusyBox&lt;/figcaption&gt;

  &lt;em&gt;
    &lt;a href=&quot;https://busybox.net/&quot; target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;BusyBox&lt;/a&gt; was created by Bruce Perens in 1995 to address the need for a compact, efficient tool set for embedded systems running Linux. At the time, most Unix utilities were too large and complex for the limited resources of embedded devices. Perens designed BusyBox to combine essential Unix tools into a single, space-saving binary, allowing developers to run key commands in environments with minimal memory and storage.
    &lt;br /&gt;&lt;br /&gt;
    The BusyBox Docker image is a streamlined Linux environment optimized for lightweight, containerized applications, testing, and quick tasks where minimalism is essential. This design allows BusyBox to deliver essential commands (like &lt;code&gt;ls&lt;/code&gt;, &lt;code&gt;cp&lt;/code&gt;, and &lt;code&gt;ping&lt;/code&gt;) in a fraction of the space required by standard Linux distributions, making the Docker image often just a 5 Mb in size.
  &lt;/em&gt;
&lt;/figure&gt;

&lt;p&gt;Once the image is downloaded, it takes about &lt;strong&gt;40 seconds&lt;/strong&gt; to copy the data between the volumes. The time is significantly less than the time it takes to restore the database dump. The data is copied, and we can start the container with the working database with the command below.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
docker run --name safari-development \
  -p 5432:5432 \
  -e POSTGRES_USER=igor \
  -e POSTGRES_DB=safari_development \
  -e POSTGRES_HOST_AUTH_METHOD=trust \
  -v safari-development:/var/lib/postgresql/data \
  -d postgres:17
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I can connect to the database and start working on the feature. When I need to reset the database, I can simply stop the container and copy the data from the template volume to the working volume again within less than a minute. This approach saves me a lot of time almost every day.&lt;/p&gt;

&lt;p&gt;To make the process easier and more automated, I created a couple of scripts that can be used to create the template and to switch between the volumes. The repository with the scripts is available &lt;a href=&quot;https://github.com/igor-alexandrov/docker-db-template&quot;&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;usage&quot;&gt;Usage&lt;/h2&gt;

&lt;p&gt;To create a template database use &lt;code&gt;docker-db-create-template.sh&lt;/code&gt;, I usually put to the &lt;code&gt;bin&lt;/code&gt; directory of the Rails project. The script that accepts two required parameters:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;code&gt;project_name&lt;/code&gt;, which is safari in our case&lt;/li&gt;
  &lt;li&gt;&lt;code&gt;file_path&lt;/code&gt;, path to the database dump (currently in SQL format)&lt;/li&gt;
&lt;/ul&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜  backend git:(master) ✗ ./bin/docker-db-create-template.sh safari ~/Downloads/safari_development.sql
Stopping container safari-development-template                  done
Deleting container safari-development-template                  done
Removing existing volume safari-development-template            done
Creating new volume safari-development-template                 done
Starting container safari-development-template                  done
	Loading /Users/igor/Downloads/safari_development.sql...
into safari_development                                         done

Database safari_development is running on port 5432

What to do next:
1. Run migrations
2. Start Rails server
3. Change the data the way you want it to be in the template
4. Stop Rails server
5. Stop the database container with the command: docker stop safari-development-template
6. Run ./bin/docker-db-use-template.sh safari to use the template
Elapsed time: 1542 seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you can connect to your database on the port 5432. Do whatever preparations in the template you need. Usually this can include creating yourself a user or any other data modifications that you will need later.&lt;/p&gt;

&lt;p&gt;When you are done with, stop your container with &lt;code&gt;docker stop safari-development-template&lt;/code&gt; command.&lt;/p&gt;

&lt;p&gt;It is time to use your template.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
➜  backend git:(master) ./bin/docker-db-use-template.sh safari
Stopping container safari-development                             done
Deleting container safari-development                             done
Removing existing volume safari-development                       done
Creating new volume safari-development                            done
Copying data from safari-development-template                     done
Starting container safari-development                             done

Database safari_development is running on port 5432
Elapsed time: 46 seconds
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Only 46 seconds and are ready to go. Start the Rails app again and work on your feature. Each time you will need to reset the database to the template simply run &lt;code&gt;./bin/docker-db-use-template.sh safari&lt;/code&gt; again.&lt;/p&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;
&lt;p&gt;There are two main takeaways from this post. The first is that you should try to be as effective as possible. When I see that some task takes a lot of time, I try to find a way to speed it up. It is true for my work as developer, CTO, and even true for my personal life. Time is the most valuable resource that we have.&lt;/p&gt;

&lt;p&gt;The second is that creating a tooling around your daily tasks can save you a lot of time. I have many scripts that I use every day. They are not perfect, but they do the job. I am excited to share them with you. For any clarifications or suggestions, feel free to reach me out on &lt;a href=&quot;https://x.com/igor_alexandrov&quot;&gt;X&lt;/a&gt;.&lt;/p&gt;
</description>
        <pubDate>Mon, 28 Oct 2024 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/use-docker-to-template-local-database</link>
        <guid isPermaLink="true">https://igor.works/blog/use-docker-to-template-local-database</guid>
        
        <category>Docker</category>
        
        <category>DevOps</category>
        
        <category>Captain Speaks</category>
        
        
      </item>
    
      <item>
        <title>Rails Thruster 101</title>
        <description>&lt;p&gt;While we are waiting for the Rails World 2024 conference to start and Kamal 2 to be released, I decided to make some preparations for the upcoming changes in the Rails ecosystem.&lt;/p&gt;

&lt;p&gt;In March 2024 Basecamp team released &lt;a href=&quot;https://github.com/basecamp/thruster/&quot;&gt;Thruster&lt;/a&gt; a small, Go-based proxy server for Rails. While the original idea of Thruster was to provide an ability to build production-ready Rails applications from a single container for the ONCE project, it will fit perfectly to the Kamal ecosystem.&lt;/p&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;isnt-it-a-redundancy&quot;&gt;Isn’t it a redundancy?&lt;/h2&gt;

&lt;p&gt;Wait? Another proxy server? Why do we need it? Allow me to explain.&lt;/p&gt;

&lt;p&gt;It doesn’t matter whether we use Traefik with Kamal v1 or kamal-proxy with Kamal v2, inside the container we still run Puma (or any other Ruby application server) that serves requests to the application. Besides this, Puma is also responsible to serving application assets – images, stylesheets, JavaScript files, etc. – to the clients. Before Kamal came into the scene, we usually had Nginx in our infrastructure schema. Nginx is a classic web server that can serve static files efficiently. Unfortunately, it is not adapted to the container-based setups as you need to manage its configuration via a config file. However, without Nginx, Puma is not the best choice to serve static files.&lt;/p&gt;

&lt;p&gt;This is where Thruster comes into play. It wraps the Puma instance and efficiently serves static files with X-Sendfile acceleration, while Puma is responsible for the dynamic content.&lt;/p&gt;

&lt;p&gt;Thruster also provides GZip compression which was available in Traefik &lt;a href=&quot;https://doc.traefik.io/traefik/middlewares/http/compress/&quot;&gt;via middleware&lt;/a&gt;, but won’t exist in kamal-proxy. GZip compression plays a crucial role in optimizing web performance by significantly reducing the size of files transmitted between a server and a client. By compressing assets like HTML, CSS, and JavaScript, GZIP decreases bandwidth usage and accelerates the loading times of web pages, providing users with a faster, more seamless browsing experience. This not only enhances user satisfaction but also improves search engine rankings, as faster websites tend to rank higher in search results. Additionally, reducing the size of data transfers lightens the load on servers, allowing them to handle more requests efficiently and lowering hosting costs.&lt;/p&gt;

&lt;p&gt;A reasonable question would be “Why I cannot do a GZIP compression in Rails?”.
Technically, you can with &lt;a href=&quot;https://github.com/rack/rack/blob/main/lib/rack/deflater.rb&quot;&gt;Rack::Deflater&lt;/a&gt;. But since Thruster is already responsible for serving public assets, it can also efficiently handle compression.&lt;/p&gt;

&lt;p&gt;Besides a compression, Thruster also provides a basic HTTP caching of public assets and HTTP/2 support.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;With Thruster your Rails application can be treated as a black box, which can serve any kind of requests efficiently.&lt;/strong&gt;&lt;/p&gt;

&lt;h2 id=&quot;how-to-use&quot;&gt;How to use?&lt;/h2&gt;

&lt;p&gt;Thruster is straightforward to use if you’re already using Puma.&lt;/p&gt;

&lt;p&gt;First, you need to add Thruster to your Gemfile:&lt;/p&gt;

&lt;pre class=&quot;language-ruby&quot;&gt;&lt;code&gt;
# Gemfile

gem &apos;thruster&apos;

&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run &lt;code&gt;bundle install&lt;/code&gt; and you are ready to go. Since Thruster is written in Go, platform specific binary will be downloaded and installed with the gem.&lt;/p&gt;

&lt;p&gt;I always create binstubs to have all the necessary commands in one place:&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
$ bundle binstubs thruster
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By default, Thruster will listen on port 80, while Puma will stay on port 3000. Knowing this we should update our application &lt;code&gt;Dockerfile&lt;/code&gt; accordingly. I assume here that your application is already dockerized. I replaced the port that is getting exposed from 3000 to 80 and added &lt;code&gt;./bin/thrust&lt;/code&gt; to the default command.&lt;/p&gt;

&lt;pre class=&quot;language-dockerfile&quot;&gt;&lt;code&gt;
# Dockerfile

# Entrypoint prepares the database.
ENTRYPOINT [&quot;/rails/bin/docker-entrypoint&quot;]

# Start server via Thruster by default, this can be overwritten at runtime
EXPOSE 80
CMD [&quot;./bin/thrust&quot;, &quot;./bin/rails&quot;, &quot;server&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The last change is to update &lt;code&gt;./bin/docker-entrypoint&lt;/code&gt; script. I always try to keep it as close to the &lt;a href=&quot;https://github.com/rails/rails/blob/main/railties/lib/rails/generators/rails/app/templates/docker-entrypoint.tt&quot;&gt;original Rails template&lt;/a&gt; as possible. Below is the final version of the script.&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
#!/bin/bash -e

# If running the rails server then create or migrate existing database
if [ &quot;${@: -2:1}&quot; == &quot;./bin/rails&quot; ] &amp;amp;&amp;amp; [ &quot;${@: -1:1}&quot; == &quot;server&quot; ]; then
  ./bin/rails db:prepare
fi

exec &quot;${@}&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That is all! Thanks to the Traefik container-based configuration, it will read the exposed port from the container and route the traffic accordingly after you will deploy the changes.&lt;/p&gt;

&lt;p&gt;After deploy will be finished, you can log in to the container and check if Thruster is running:&lt;/p&gt;

&lt;pre class=&quot;language-bash&quot;&gt;&lt;code&gt;
rails@docker:~$ ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
rails          1  0.0  0.3 1232848 13124 ?       Ssl  09:26   0:06 /usr/local/bundle/ruby/3.3.0/gems/thruster-0.1.8-x86_64-linux/exe/x86_64-linux/thrust ./bin/rails server
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Since there are no visible cons of using Thruster in your Rails application, I highly recommend using it. It can improve the performance of your application and reduce the load on the server. It is also a good idea to use it as a preparation for the upcoming Kamal 2 release.&lt;/p&gt;
</description>
        <pubDate>Mon, 23 Sep 2024 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/rails-thruster-101</link>
        <guid isPermaLink="true">https://igor.works/blog/rails-thruster-101</guid>
        
        <category>Ruby</category>
        
        <category>Rails</category>
        
        <category>DevOps</category>
        
        <category>kamal</category>
        
        
      </item>
    
      <item>
        <title>Odd Ruby return values</title>
        <description>&lt;p&gt;Earlier this week I published a &lt;a href=&quot;https://x.com/igor_alexandrov/status/1827955386365677774&quot;&gt;tweet that made some buzz&lt;/a&gt; in the community. To be honest, I didn’t expect that so many people would be interested in this topic. About 29000 views and 1600 votes is quite an impressive result for 9 lines of code.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;The tweet was about the following code snippet:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;class Klass
  def self.square(value)
    if value &amp;gt; 0
      value * value
    end
  end
end

puts Klass.square(0)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The question was: what is the result of the &lt;code&gt;Klass.square(0)&lt;/code&gt; method call?&lt;/p&gt;

&lt;h2 id=&quot;tldr&quot;&gt;TL;DR&lt;/h2&gt;

&lt;p&gt;The result of the &lt;code&gt;Klass.square(0)&lt;/code&gt; method call is &lt;code&gt;nil&lt;/code&gt;. From 1600 votes, about 1500 people gave the correct answer.&lt;/p&gt;

&lt;h2 id=&quot;explanation&quot;&gt;Explanation&lt;/h2&gt;

&lt;p&gt;Every expression in Ruby has a value.&lt;/p&gt;

&lt;p&gt;A conditional statement in Ruby is an expression that returns &lt;code&gt;nil&lt;/code&gt; if the conditional is &lt;code&gt;false&lt;/code&gt;. Ruby methods return the last expression in the method body.&lt;/p&gt;

&lt;p&gt;So, in the code snippet above, 0 is not greater than 0, so the &lt;code&gt;if&lt;/code&gt; statement returns &lt;code&gt;nil&lt;/code&gt;. The &lt;code&gt;Klass.square&lt;/code&gt; method returns the result of the &lt;code&gt;if&lt;/code&gt; statement (because it is the last expression), which is &lt;code&gt;nil&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Elementary, right? Yes, but since there were about 100 people who gave the wrong answer (0), even such simple things can be tricky and odd.&lt;/p&gt;

&lt;h2 id=&quot;more-odd-examples&quot;&gt;More odd examples&lt;/h2&gt;

&lt;p&gt;In the comments to the tweet, &lt;a href=&quot;https://x.com/lucianghinda/status/1828077212370714890&quot;&gt;Lucian Ghinda pointed&lt;/a&gt; to a similar, odd example originally &lt;a href=&quot;https://x.com/braindeaf/status/1825482461591024056&quot;&gt;found by Rob Lacey&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It turns out that local variable assignment in Ruby assigns nil even if the right part of the expression is not defined.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;irb(main):001&amp;gt; local_var = undefined_var
(irb):1:in `&amp;lt;main&amp;gt;&apos;: undefined local variable or method `undefined_var&apos; for main:Object (NameError)

local_var = undefined_var
            ^^^^^^^^^^^^^
  from /Users/igor/.rbenv/versions/3.2.3/lib/ruby/gems/3.2.0/gems/irb-1.13.2/exe/irb:9:in `&amp;lt;top (required)&amp;gt;&apos;
  from /Users/igor/.rbenv/versions/3.2.3/bin/irb:25:in `load&apos;
  from /Users/igor/.rbenv/versions/3.2.3/bin/irb:25:in `&amp;lt;main&amp;gt;&apos;
irb(main):002&amp;gt; local_var
=&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To be honest, I didn’t know about this behavior before.&lt;/p&gt;

&lt;h2 id=&quot;why-do-i-ask-this-in-interviews&quot;&gt;Why do I ask this in interviews?&lt;/h2&gt;

&lt;p&gt;In my original post, I mentioned that I ask this question in interviews. This triggered a discussion about whether it is a good idea to ask such questions in interviews.&lt;/p&gt;

&lt;p&gt;Yes, I believe that at the beginning of your career, it is crucial to understand how the language you are working with works. It is important to know all the nuances and dive as deep as you can. Even if the candidate doesn’t know the answer, which is usual and normal in entry-level positions, he can always demonstrate his thinking curve which, start discussion and try to explain the potential behavior. Focusing on how a candidate thinks and approaches problems can reveal a lot about their potential and willingness to learn, which is especially important early in their careers.&lt;/p&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;Today you learned, or, I hope, you remembered, that every expression in Ruby has a value. Conditional statements in Ruby are expressions that return &lt;code&gt;nil&lt;/code&gt; if the conditional is &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;
</description>
        <pubDate>Fri, 30 Aug 2024 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/odd-ruby-return-values</link>
        <guid isPermaLink="true">https://igor.works/blog/odd-ruby-return-values</guid>
        
        <category>Ruby</category>
        
        <category>Rails</category>
        
        <category>Today You Learned</category>
        
        
      </item>
    
      <item>
        <title>Redirect and return in Rails controllers</title>
        <description>&lt;p&gt;Premature returning from a controller action is a common idiom in Rails applications. I &lt;a href=&quot;https://x.com/igor_alexandrov/status/1825463488954741103&quot;&gt;asked my followers&lt;/a&gt; in Twitter about whether they know or know how to do this correctly, and I am glad to see that most of them gave the correct answer. Let’s dive into the details.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;Before we start, I suggest you to take a look at the post, I mentioned above, to see the answers and to try to solve the problem by yourself. If, for some reason, you can’t or don’t want to do this, I created a screenshot for you.&lt;/p&gt;

&lt;figure class=&quot;not-prose my-8 grid grid-cols-1 justify-items-center py-2&quot;&gt;
  &lt;img src=&quot;/assets/images/posts/2024-08-23/twitter-post.jpeg&quot; alt=&quot;Original Twitter post with answers&quot; style=&quot;max-width: 600px&quot; /&gt;

  
  &lt;figcaption class=&quot;mt-2 block text-center text-sm text-gray-600&quot;&gt;
    Original Twitter post with answers
  &lt;/figcaption&gt;
  
&lt;/figure&gt;

&lt;p&gt;Most of those who votes made the right choice. &lt;strong&gt;Correct answers were options 1 and 2&lt;/strong&gt;. I usually use the first one, but the second option was also correct.&lt;/p&gt;

&lt;p&gt;To understand why the first and the second options are correct, I recommend you to read &lt;a href=&quot;https://ruby-doc.com/docs/ProgrammingRuby/language.html#table_18.4&quot;&gt;the table of operator precedence in Ruby&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;-operator-in-options-2-and-3&quot;&gt;&amp;amp;&amp;amp; operator in options 2 and 3&lt;/h2&gt;

&lt;p&gt;Using &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; in options 2 and 3 is a bit tricky.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;redirect_to(sign_in_path) &amp;amp;&amp;amp; return
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the expression above, &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; operator get the result of &lt;code&gt;redirect_to(sign_in_path)&lt;/code&gt; as the left operand and &lt;code&gt;return&lt;/code&gt; as the right operand. This expression will work correct.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;redirect_to sign_in_path &amp;amp;&amp;amp; return
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, without explicit brackets, &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; get the result of &lt;code&gt;sign_in_path&lt;/code&gt; as the left operand and &lt;code&gt;return&lt;/code&gt; as the right operand. The value of the return keyword is &lt;code&gt;nil&lt;/code&gt;, so the expression above can be rewritten as:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;redirect_to sign_in_path &amp;amp;&amp;amp; nil
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Whatever &lt;code&gt;&amp;amp;&amp;amp; nil&lt;/code&gt; will return &lt;code&gt;nil&lt;/code&gt;, and &lt;code&gt;redirect_to&lt;/code&gt; will be called with &lt;code&gt;nil&lt;/code&gt; as an argument, which finally will raise an error.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;ActionController::ActionControllerError in TimeOffsController#new
Cannot redirect to nil!
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;option-4&quot;&gt;Option 4&lt;/h2&gt;

&lt;p&gt;There was no way to vote for the fourth option directly, but there were a few who said that all options were correct.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;def show
  redirect_to sign_in_path unless current_user

  @time_off = current_user.time_offs.find(params[:id])

  render @time_off
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In Rails, &lt;code&gt;redirect_to&lt;/code&gt; does only sets correct response headers and status code, but it doesn’t stop the execution of the action. In the example above, if &lt;code&gt;current_user&lt;/code&gt; is &lt;code&gt;nil&lt;/code&gt;, you will face DoubleRenderError.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;AbstractController::DoubleRenderError in TimeOffsController#new
Render and/or redirect were called multiple times in this action.
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;upd-difference-between--and-and&quot;&gt;UPD. Difference between &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; and &lt;code&gt;and&lt;/code&gt;&lt;/h2&gt;

&lt;p&gt;Above in the post, I posted the link to the table of operator precedence in Ruby. Both &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; and &lt;code&gt;and&lt;/code&gt; are logical operators in Ruby, but they have different precedence, &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; has higher precedence than &lt;code&gt;and&lt;/code&gt;. This difference in precedence can lead to unexpected behavior when they are used in complex expressions.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;# Using &amp;amp;&amp;amp;
a = true &amp;amp;&amp;amp; false
b = false &amp;amp;&amp;amp; true

puts a # =&amp;gt; false
puts b # =&amp;gt; false

# Using and
c = true and false
d = false and true

puts c # =&amp;gt; true
puts d # =&amp;gt; false
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Pretty interesting, right?&lt;/p&gt;

&lt;p&gt;In the first case &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;, the assignment happens after evaluating the expression, so &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are both assigned the result of the logical operation &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;In the second case &lt;code&gt;and&lt;/code&gt;, the assignment happens before the logical operation because &lt;code&gt;and&lt;/code&gt; has lower precedence than &lt;code&gt;=&lt;/code&gt;. So &lt;code&gt;c&lt;/code&gt; is first assigned true, and then the logical and operation is evaluated, which does not affect the assignment.&lt;/p&gt;

&lt;p&gt;Let’s take a look at the another example.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-ruby&quot;&gt;# Using &amp;amp;&amp;amp;
a = b = false &amp;amp;&amp;amp; true
puts a # =&amp;gt; false
puts b # =&amp;gt; false

# Using and
c = d = false and true
puts c # =&amp;gt; false
puts d # =&amp;gt; false
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt;, both &lt;code&gt;a&lt;/code&gt; and &lt;code&gt;b&lt;/code&gt; are assigned the result of &lt;code&gt;false &amp;amp;&amp;amp; true&lt;/code&gt;, which is &lt;code&gt;false&lt;/code&gt;.
With and, &lt;code&gt;d = false&lt;/code&gt; is evaluated first (due to and’s lower precedence), and then &lt;code&gt;c = d&lt;/code&gt; is assigned.&lt;/p&gt;

&lt;p&gt;You should be careful when using &lt;code&gt;and&lt;/code&gt; and &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; in complex expressions. It is better to use &lt;code&gt;&amp;amp;&amp;amp;&lt;/code&gt; for logical operations, while &lt;code&gt;and&lt;/code&gt; can be used to control flow.&lt;/p&gt;

&lt;h2 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h2&gt;

&lt;p&gt;Despite the fact my post was about Ruby operator precedence, there were people who suggested that it is better to use &lt;code&gt;before_action&lt;/code&gt; for such kind of checks. I agree. I will try to be more explicit in my future posts and will provide more context.&lt;/p&gt;

&lt;p&gt;Nevertheless, I hope you learned something new. Stay tuned!&lt;/p&gt;
</description>
        <pubDate>Fri, 23 Aug 2024 00:00:00 +0400</pubDate>
        <link>https://igor.works/blog/redirect-and-return-in-rails-controllers</link>
        <guid isPermaLink="true">https://igor.works/blog/redirect-and-return-in-rails-controllers</guid>
        
        <category>Ruby</category>
        
        <category>Rails</category>
        
        <category>Today You Learned</category>
        
        
      </item>
    
  </channel>
</rss>
