<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Anton Chisliuk]]></title><description><![CDATA[Anton Chisliuk]]></description><link>https://antonchisliuk.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 30 Nov 2026 22:32:57 GMT</lastBuildDate><atom:link href="https://antonchisliuk.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Freezing signed documents in Postgres with triggers]]></title><description><![CDATA[In my Rails 8 app the model says a signature is read-only. The database makes sure of it.]]></description><link>https://antonchisliuk.hashnode.dev/freezing-signed-documents-in-postgres-with-triggers</link><guid isPermaLink="true">https://antonchisliuk.hashnode.dev/freezing-signed-documents-in-postgres-with-triggers</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[Rails]]></category><category><![CDATA[Databases]]></category><category><![CDATA[SQL]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Anton Chisliuk]]></dc:creator><pubDate>Sun, 29 Nov 2026 16:58:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0561300a0ab38c5b277100/04c99c7d-1e46-4da0-9fe2-24ec90b463a0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When a customer signs an estimate in the app I'm building, three things get written to the database: the version of the estimate they saw, the signature itself, and a log of events around it (sent, viewed, signed). After that, those rows should never change. If the contractor and the customer ever remember the deal differently, the stored version is the record both of them can look at. It's worth nothing if anyone could have edited it afterwards.</p>
<p>The app is <a href="https://quoza.app/?utm_source=hashnode&amp;utm_medium=referral&amp;utm_campaign=selfpub_2026_11">Quoza</a>, an estimate app for trade businesses of one to five people. It runs on Rails 8 and Postgres. This post is about how I made those rows read-only in the database with triggers, and what that changed in the Rails code and in the tests.</p>
<h2>Why the model isn't enough</h2>
<p>The model has its own guard. <code>Signature#readonly?</code> returns true once the record is sealed, and <code>before_destroy</code> raises. That covers <code>update!</code> and <code>destroy</code> on a loaded record.</p>
<p>It doesn't cover <code>update_all</code>, <code>update_column</code>, <code>delete_all</code>, a raw <code>execute</code> inside a data migration, or a quick fix typed into a production console. All of them skip callbacks and validations. So does any background job someone writes next year without knowing the rule.</p>
<p>So the same rule also lives in Postgres. The model guards fail early with a clear error. The triggers are the last line: whatever code writes to the table, the database refuses.</p>
<h2>The simple case: append-only</h2>
<p><code>signature_events</code> is a log. Rows are inserted and never touched again. One function covers it, and I reuse it for other log tables:</p>
<pre><code class="language-sql">CREATE FUNCTION quoza_append_only_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  RAISE EXCEPTION '% is append-only: % forbidden', TG_TABLE_NAME, TG_OP
    USING ERRCODE = 'restrict_violation';
END;
$$;

CREATE TRIGGER signature_events_append_only
  BEFORE UPDATE OR DELETE ON signature_events
  FOR EACH ROW EXECUTE FUNCTION quoza_append_only_guard();
</code></pre>
<p><code>TG_TABLE_NAME</code> and <code>TG_OP</code> put the table and the operation into the message, so the same function works on any table. INSERT isn't in the trigger, so new events are written as usual.</p>
<p>Each event also stores a SHA-256 hash of the previous event's hash plus its own fields. <code>SignatureEvent.chain_valid?</code> walks the chain and recomputes every hash, so a row changed behind the trigger's back breaks the chain.</p>
<h2>Frozen except for a few columns</h2>
<p>Sent estimate versions are harder. A sent version has to stay exactly as the customer saw it, but one thing can still happen to it: a newer version replaces it. The contractor edits the estimate and sends it again, and the old version gets <code>superseded_at</code> and <code>superseded_by_id</code>. Drafts stay fully editable and can be deleted.</p>
<p>I didn't want to list every frozen column in the trigger, because someone adds a column next month and forgets the trigger. So the function turns both rows into <code>jsonb</code>, removes the columns that may change, and compares what's left:</p>
<pre><code class="language-sql">CREATE FUNCTION quoza_sent_quote_versions_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF OLD.kind &lt;&gt; 'sent' THEN
    IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
    IF NEW.kind = 'sent' THEN
      RAISE EXCEPTION 'quote_version %: a draft step cannot become sent', OLD.id
        USING ERRCODE = 'restrict_violation';
    END IF;
    RETURN NEW;
  END IF;
  IF TG_OP = 'DELETE' THEN
    RAISE EXCEPTION 'sent quote_version % is immutable: DELETE forbidden', OLD.id
      USING ERRCODE = 'restrict_violation';
  END IF;
  IF (to_jsonb(NEW) - ARRAY['superseded_at', 'superseded_by_id', 'updated_at'])
     IS DISTINCT FROM
     (to_jsonb(OLD) - ARRAY['superseded_at', 'superseded_by_id', 'updated_at']) THEN
    RAISE EXCEPTION 'sent quote_version % is immutable: only superseding is allowed', OLD.id
      USING ERRCODE = 'restrict_violation';
  END IF;
  RETURN NEW;
END;
$$;
</code></pre>
<p>With an allow-list, a new column is frozen by default. If it has to be editable after sending, you change the function on purpose, in a migration, where a reviewer sees it. A draft also can't be turned into a sent version with an UPDATE. Sending always inserts a new row.</p>
<h2>Sealing: one update, then never again</h2>
<p>A <code>signatures</code> row gets exactly one update after it's created. The signed PDF is rendered, its SHA-256 goes into <code>document_sha256</code>, and from then on the row is sealed:</p>
<pre><code class="language-sql">IF TG_OP = 'DELETE' THEN
  RAISE EXCEPTION 'signatures are immutable: DELETE forbidden (id %)', OLD.id
    USING ERRCODE = 'restrict_violation';
END IF;
IF OLD.document_sha256 IS NOT NULL THEN
  RAISE EXCEPTION 'signature % is sealed: UPDATE forbidden', OLD.id
    USING ERRCODE = 'restrict_violation';
END IF;
IF (to_jsonb(NEW) - ARRAY['document_sha256', 'pdf_generated_at', 'updated_at'])
   IS DISTINCT FROM
   (to_jsonb(OLD) - ARRAY['document_sha256', 'pdf_generated_at', 'updated_at']) THEN
  RAISE EXCEPTION 'signature % evidence columns are immutable', OLD.id
    USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
</code></pre>
<p>Before sealing, only the hash and its timestamp can be set. After sealing, nothing. The signer's name, IP address, user agent, consent text version and the amounts are frozen from the first insert.</p>
<p>The PDF bytes live in Postgres too, through a database service for Active Storage. Later I added the same kind of guard on the Active Storage tables. A file attached as <code>signed_pdf</code> is accepted only if <code>encode(sha256(f.data), 'hex')</code> equals the signature's <code>document_sha256</code>, so the database checks that the stored file is the one that was hashed.</p>
<h2>The Rails side</h2>
<p><code>schema.rb</code> can't hold functions or triggers. With <code>config.active_record.schema_format = :sql</code>, Rails dumps <code>db/structure.sql</code>, and the test database is built from it, triggers included. Without that switch the tests would run against a database with no triggers and pass for the wrong reason.</p>
<p>The triggers themselves are plain <code>execute &lt;&lt;~SQL</code> migrations, with a <code>down</code> that drops them.</p>
<p>The model keeps its own guard:</p>
<pre><code class="language-ruby">class Signature &lt; ApplicationRecord
  MUTABLE_UNTIL_SEALED = %w[document_sha256 pdf_generated_at updated_at].freeze

  validate :evidence_unchanged, on: :update
  before_destroy { raise ActiveRecord::ReadOnlyRecord, "signatures are retained" }

  def sealed? = document_sha256_in_database.present?
  def readonly? = (persisted? &amp;&amp; sealed?) || super

  private

  def evidence_unchanged
    changed_evidence = changed - MUTABLE_UNTIL_SEALED
    errors.add(:base, "signature evidence is immutable") if changed_evidence.any?
  end
end
</code></pre>
<p>The same column list is in Ruby and in SQL. That's duplication, and I keep it. The Ruby check gives a validation error the app can handle. The SQL check catches everything else. When Postgres refuses a write, Rails raises <code>ActiveRecord::StatementInvalid</code> with the trigger's message, and the transaction rolls back.</p>
<p><code>sealed?</code> reads <code>document_sha256_in_database</code>, the stored value. Assigning the attribute in memory doesn't make the record look sealed before it's saved.</p>
<h2>Testing the database, not the model</h2>
<p>A test that calls <code>signature.update!</code> only tests the Ruby guard. To test the triggers, the tests go around the model on purpose and send raw SQL:</p>
<pre><code class="language-ruby">def sql(statement)
  ActiveRecord::Base.transaction(requires_new: true) do
    ActiveRecord::Base.connection.execute(statement)
  end
end

def assert_db_rejects(statement)
  error = assert_raises(ActiveRecord::StatementInvalid) { sql(statement) }
  assert_match(/immutable|append-only|sealed/, error.message)
end

test "signature_events are append-only" do
  event = @g[:signature_event]
  assert_db_rejects "UPDATE signature_events SET event = 'signed' WHERE id = #{event.id}"
  assert_db_rejects "DELETE FROM signature_events WHERE id = #{event.id}"
end
</code></pre>
<p><code>requires_new: true</code> wraps each statement in a savepoint. Without it, the first refused statement aborts the test's transaction, and every query after it fails with "current transaction is aborted".</p>
<p>The same file checks the other direction too: drafts can still be updated and deleted, and a sent version that nobody signed can still be superseded. A trigger that blocks too much is also a bug.</p>
<h2>What it costs</h2>
<p>Deleting old data takes a deliberate step. A retention purge has to run as the database owner with <code>ALTER TABLE ... DISABLE TRIGGER</code> written out explicitly. I'm fine with that, because I want deleting a signature to be hard.</p>
<p>Changing a rule means a migration that replaces a function. Two rules came later this way. A signed version can't be superseded. And nobody can sign a version that has already been superseded: a <code>BEFORE INSERT</code> trigger on <code>signatures</code> checks the version row, and it takes that row <code>FOR SHARE</code> first, so a send running at the same moment can't slip past it.</p>
<p>The trigger messages are for developers. A user should never see one. If a user hits one, the bug is in the app code above it.</p>
<p>If you've solved this another way, for example with <code>REVOKE UPDATE</code> on the app's database role or with a separate audit table, how did it hold up?</p>
]]></content:encoded></item><item><title><![CDATA[Building a phone-first estimate flow with Rails 8, Turbo and Stimulus]]></title><description><![CDATA[Disclosure: this article was created with the help of AI. AI tools drafted it from my codebase and project notes, and it was edited and checked against the…]]></description><link>https://antonchisliuk.hashnode.dev/building-a-phone-first-estimate-flow-with-rails-8-turbo-and-stimulus</link><guid isPermaLink="true">https://antonchisliuk.hashnode.dev/building-a-phone-first-estimate-flow-with-rails-8-turbo-and-stimulus</guid><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[hotwire]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Anton Chisliuk]]></dc:creator><pubDate>Tue, 24 Nov 2026 10:37:13 GMT</pubDate><content:encoded><![CDATA[<p><em>Disclosure: this article was created with the help of AI. AI tools drafted it from my codebase and project notes, and it was edited and checked against the code before publishing. I'm the founder of the app it describes.</em></p>
<p>I'm building an estimate and invoice app for small trade businesses: plumbers, painters, handymen, crews of one to five people. The contractor writes an estimate on their phone and texts the customer a link. The customer opens it, picks an option, signs and sees how to pay the deposit.</p>
<p>So the app has two very different users. One opens it many times a day and has it on their home screen. The other opens it once, from a text message, maybe on one bar of signal in a basement. This post is about how I split the front end between them in one Rails 8 app, and a few choices that came out of designing for phones first.</p>
<h2>The stack</h2>
<p>It's one Rails 8.1 monolith on Postgres. Hotwire (Turbo and Stimulus) on the front end, Tailwind v4 for styles, importmap instead of a JS bundler. Background jobs run on Solid Queue, and in production Solid Queue runs inside the Puma process through its plugin, so the whole app is one web service plus a database. PDFs come from Prawn. The contractor side is a PWA built on the manifest and service worker that Rails 8 generates.</p>
<p>Nothing exotic. The interesting part is what loads where.</p>
<h2>Two pages, two budgets</h2>
<p>The contractor is signed in, has the app on the home screen and uses it every day. Turbo makes navigation there feel close to a native app, so loading Turbo, dozens of Stimulus controllers and Turbo Streams for live updates is fine.</p>
<p>The customer has never heard of the app and opens one link. That page has to render fast and work with as little JavaScript as possible.</p>
<p>So the customer page has its own layout and its own importmap entry point. It loads Stimulus and a handful of controllers. No Turbo, no ActionCable, no third-party scripts. The budget I set for that page is under 50 KB of gzipped JS.</p>
<p>Here is the entry point, trimmed to the controllers this post talks about:</p>
<pre><code class="language-js">// public_quote.js: Stimulus plus the page's controllers. No Turbo, no ActionCable, no SDKs.
import { Application } from "@hotwired/stimulus"
import QuoteChoiceController from "controllers/quote_choice_controller"
import CopyController from "controllers/copy_controller"
import ConnectivityController from "controllers/connectivity_controller"

const application = Application.start()
application.register("quote-choice", QuoteChoiceController)
application.register("copy", CopyController)
application.register("connectivity", ConnectivityController)
</code></pre>
<p>Without Turbo, forms on that page work the old way: POST, redirect, full render. Where the contractor side would answer with a Turbo Stream, the customer side does a normal round trip. On a page someone visits once, a full reload after signing is fine.</p>
<h2>Load the signature pad only when it's needed</h2>
<p>The signature controller is the heaviest one on the page, and some visitors never sign. So it's imported on demand: right away if the page renders a sign block, or on the first tap on Draw.</p>
<pre><code class="language-js">let signatureLoading
const loadSignature = () =&gt; signatureLoading ||= import("controllers/signature_controller")
  .then(({ default: SignatureController }) =&gt; application.register("signature", SignatureController))

if (document.querySelector("[data-controller~=signature]")) loadSignature()
</code></pre>
<p>Importmap handles the dynamic import without a build step.</p>
<h2>The browser shows the total, the server decides it</h2>
<p>When the customer picks an option or ticks an extra, the total and the deposit update on the spot. A Stimulus controller does the arithmetic on values the server rendered into the page.</p>
<p>That number is for display only. When the customer taps Accept &amp; sign, the server recalculates everything from the stored lines. Money is stored as integer cents plus a currency code, never as floats, and every total that counts is computed on the server.</p>
<p>The customer's choice survives a reload through sessionStorage, so a dropped connection or an accidental refresh doesn't reset their pick.</p>
<h2>Sending from the contractor's own phone</h2>
<p>I wanted the estimate to come from the contractor's own number, one the customer already knows, so the app doesn't send SMS through a gateway. Sending has two steps. First the server records the send and creates the link. Then the phone does its part: it opens the share sheet through the Web Share API where that exists, or opens Messages with an <code>sms:</code> URL and the text filled in, or copies the link.</p>
<p>Recording the send first means the estimate status is right even if the user closes Messages without sending.</p>
<p>SMS text has a trap. One character outside the GSM-7 set, like a curly apostrophe or an em dash, switches the whole message to UCS-2, and a single segment drops from 160 characters to 70. A design lint script checks every SMS string for that.</p>
<h2>Offline: show it, don't queue it</h2>
<p>Trade work happens in basements and on roofs. A Stimulus controller listens for the browser's online and offline events, shows a bar, and marks guarded buttons <code>aria-disabled</code> with a reason next to them.</p>
<p>Nothing that touches signatures or money gets queued while offline. A deferred Accept &amp; sign that fires an hour later is harder to reason about than a disabled button that says why. Safari doesn't support the Background Sync API either, so a queue there would only drain the next time the app is opened.</p>
<h2>Voice in, text out</h2>
<p>Contractors can describe a job out loud. The recorder is a small Stimulus controller around MediaRecorder: tap to start, tap to stop (never hold), with a visible timer and an automatic stop at a time limit. It only records and dispatches an event with the audio blob. The server transcribes the audio and puts the text into the field the contractor was filling in.</p>
<p>Tap to start was deliberate. Holding a button while you talk is awkward in gloves, or with a tape measure in the other hand.</p>
<h2>What I'd tell someone starting the same way</h2>
<p>Decide early which pages belong to a signed-in user and which belong to a stranger, and give them separate layouts and entry points. Adding a "lite" page later is harder than starting with one.</p>
<p>And test on a cheap phone with a bad connection, not only on the laptop you build on.</p>
]]></content:encoded></item></channel></rss>