Welcome to My Blog.

Here, you will find posts, links, and more about code (primarily Ruby), business (bootstrapped SaaS), and a little of everything in between.

It hurts my feelings when one flaky system test causes the whole bar to turn red.

flakey.png

#

When a HTTP Post Becomes a Patch

I was implementing the previews in PhrontPage.

Part of this involves grabbing the current form and sending the data via HTTPost (using requestjs-rails) to the server and then letting turbo_stream do its thing and update the screen.

const form = new FormData(formElement)
const response = await post(this.urlValue, {
   body: form,
   responseKind: "turbo-stream"
})

Full source in preview_controller.js

This was wired up to a controller like this:

post "/previews", to: "previews#show"

When working with new Posts or Pages, everything worked as expected.

However, once I tried to preview an existing Post or Page, I started getting 404 errors. Thankfully, it did not take me long to spot the error.

I believe it was Rails 4 when the switch was made to use the Patch verb for updates. Browsers do not typically support Patch. To get around this, Rails (and other frameworks) add a hidden field called _method.

patch.png

The browser declares a post request on the form. However, when Rails spots the '_method` parameter, it knows to look for the matching route. In my case, this did not exist at the time.

There are some simple fixes for this:

  1. Remove the _method from my FormData
  2. Supply a different route to handle existing Posts and Pages
  3. Update the route to work for both Post and Patch

I went with option #3. For the preview feature, it does not matter if the content already exists. I need to take what you have on the form and send it to the server.

The updated route looks like this:

match "/previews", to: "previews#show", via: [:patch, :post]
#

Rails Direct Uploads to A Custom Folder

One of my must-have features for PhrontPage was drag-and-drop direct uploads to a plain Markdown editor. I have always liked this functionality on GitHub issues. Rails ships with Trix support for dropping files on an editor, but that is not how I want to write.

I had bookmarked this example by Jeremy Smith a while ago, and it was a great help to get this feature implemented.

However, after a bit of testing, I quickly found my R2 bucket to be a bit messy and wanted to, at a minimum, direct all my blog uploads to a single folder. Surprisingly, there is not a built-in way to do this.

I created a custom ActiveStorage Service that derives from the S3Service and provides an option to append a folder to all the uploads that go through the service.

require "active_storage/service/s3_service"
module ActiveStorage
  class Service
    class S3WithPrefixService < S3Service

      def path_for(key)
        "uploads/#{key}"
      end

      def object_for(key)
        bucket.object(path_for(key))
      end
      
    end
  end
end

The full PhrontPage implements can be seen here, with code to pull the folder from an ENV variable and handle any extra "/". The one below is just the basics to get started.

Once added to your project, all you have to do is add it to your storage.yml file, and you should be all set.

#

Stimulus Controllers with a Single Target

For Stimulus controllers with a single target, I have been defaulting to using this.Element instead of requiring a target.

However, some don't like this approach since your controller essentially becomes hardcoded to your markup.

I was updating the footer of this site earlier today and decided to use the following pattern:

  static targets = ['footer']
  footerElement() {
    return (this.hasFooterTarget && this.footerTarget) || this.element
  }
  1. If the target exists, use it
  2. If there is no target, then use the element.

This feels like a happy middle ground. There is no need for the wasted target declaration, but if the markup ever gets more complicated, no code changes are needed in the controller.

If you are curious, here is the entire controller.

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["footer"]

  connect() {
    this.adjustFooter()
    window.addEventListener('resize', this.adjustFooter)
  }

  disconnect() {
    window.removeEventListener('resize', this.adjustFooter)
  }

  footerElement() {
    return (this.hasFooterTarget && this.footerTarget) || this.element
  }

  adjustFooter = () => {
    const footer = this.footerElement()
    if (document.body.offsetHeight <= window.innerHeight) {
      footer.classList.add('fixed', 'bottom-0')
      footer.classList.remove('relative')
    } else {
      footer.classList.add('relative')
      footer.classList.remove('fixed', 'bottom-0')
    }
  }
}

When I initially built the app, I had the footer permanently fixed at the bottom. However, when reading the site, I hated the extra space the footer was taking up being fixed. Now, we get the best of both worlds with the following stimulus controller. On pages with limited content, the footer is fixed at the bottom of the page. The footer goes back to being relative on pages with a full screen of content (who writes more than 200 characters at a time these days....😀).

#

Handling a Stuck Heroku Release Command (Maybe)

I am unsure how to title this post, but it feels like a good idea to share what happened so that you have some steps to follow if you are in a bit of a panic.

First, here is what happened. Earlier today, I deployed a change that would add a column to a table. There was no backfill on the column. There are no required indexes. Nothing. It's a blank column on a relatively small (20k rows) table. I even held the code that would use this table for a second deployment.

Our Heroku deploys have been taking quite a while recently (15 minutes or so). I haven't had time to dig into why yet, so I wasn't overly concerned about the duration initially. Then I got the first ping that something was offline (Sidekiq error queue). That one felt unrelated. Our monitoring is set to notify us anytime the error queue has more than 100 items. Shortly after, I received notifications that other services were unavailable (timing out). A quick check on the recent deployment shows that the release phase has been running for 20 minutes.

At this point, I decide it is time to kill the deployment. I commnd+D the terminal and checked the current processes on Heroku (heroku ps). I can see the release command is still running. The next thing to check is the database. I can console into the database and other apps that use this same database are all functioning as expected. In addition, as far as I can tell, all the background jobs for this app are still running as expected (we use Sidekiq+Redis, but ultimately all work is done against the PG database).

To be safe, I ran pg:diagnose and could see long-running queries against the table I was attempting to migrate.

Next, I focused on killing the release phase process. In nearly 12 years of using Heroku, I have never had to kill a running process. I find references to ps:stop and ps:kill. Both report they worked, but running us ps, I can see the process is still running. It turns out that you need to include the process type as well: heroku ps:kill release.2343. Better output here would have been helpful.

While this killed the process, the app's state did not improve. I restarted the processes, which again did not fix the problem. Finally, I figured something was off with the app state, so I rolled back to a previous update (note: the new deploy was never fully deployed and unavailable). This appeared to fix things for a few seconds, but everything on the main app again began to time out.

I checked heroku pg:diagnose again and could see the same long-running queries were still there. There were about 40 or so of them, but I couldn't get the output in a state where I could quickly grab the PIDs to kill each process, so I went ahead and ran heroku pg: killall. After this, I restarted the main app (and related apps), and everything appears to be working well.

So the takeaways:

  1. Never deploy before coffee. The mind is not ready for this kind of stress.
  2. My best guess is that the connection pool for the main web app somehow got into a bad state. Killing all the connections, I was able to reset it.

I still have to deploy again, but I assume this was a freak condition.

#

Adding Execute Permission to Script in Git

With my SQLite backup script, I mentioned you need to add execute permission after you deploy.

However, I cloned a Rails app off of GitHub today and noticed that the bin/setup worked as expected and had proper execute permissions. 👀

I eventually found my way to the git's update-index command:

Modifies the index. Each file mentioned is updated into the index and any unmerged or needs updating state is cleared.

That description is clear as mud. 😛

But digging further is this option: --chmod=(+|-)x

Set the execute permissions on the updated files.

So here is how to use it.

  1. Add a new script file or modify an executing one (even with just a comment). This is important because update-index will not take effect unless you commit to some change.
  2. Add the change to git: git add bin/backup
  3. Execute update-index: `git update-index --chmod=+x bin/backup
  4. Commit the change: git commit -m "Now with execute permission"
#

Ruby Sub vs. Gsub

A little Ruby distinction I had not seen (or remembered seeing) before.

In Ruby, both String#sub and String#gsub are methods used for string substitution, but they have a subtle difference:

String#sub: This method performs a substitution based on a regular expression pattern, replacing only the first occurrence that matches the pattern.

str = "hello world"
new_str = str.sub(/o/, "a")
puts new_str

Output: hella world

String#gsub: This method also performs a substitution based on a regular expression pattern, but it replaces all occurrences that match the pattern within the string.

str = "hello world"
new_str = str.gsub(/o/, "a")
puts new_str

Output: hella warld

Hat tip to ChatGPT, who answered this question for me.

#

Configuring the SQLite BackUp Script for Hatchbox

Getting the SQLite BackUp Script running on Hatbox took a little extra work.

First, to get access to the ENV variables (assuming you are not hardcoding), you need to add the following:

cd /home/deploy/YOUR_APP_NAME/current
eval "$(/home/deploy/.asdf/bin/asdf vars)"

Second, where should I put the script? I would like to put it in the Rails bin directory. This works for getting it up to the server. However, anytime you deploy the execute permission on the script is lost.

My next attempt was to add a folder called bin to the shared directory. I set up a symlink to the file ln -sf ../../current/bin/backup backup and then set the execute permission to chmod +x backup. This worked, but the execute permission was again lost after a deployment.

Ultimately, I copied the script to the shared/bin directory and reset the execute permission. If I change it, I must remember to update the copy, but now it works.

Finally, I went to the HatchBox cron page for my app and configured the following to execute several times a day:

(cd ../shared/bin ; ./backup)

HatchBox cron jobs start in your current directory. We need to navigate to the bin folder before we can finally execute the backup.

#

SQLite BackUp to S3

I recently moved HowIVSCode to HatchBox. As part of their setup, they provide a shared folder for each application persisted across deployments.

However, at this time, there is no option to back up that data.

Side Note: Digital Ocean provides server backups, which would likely work, but I would rather my backups exist outside the network managing my servers.

What I ended up doing was writing a script that does the following:

  1. Loops through all the SQLite files in a given directory
  2. Uses the SQLite .backup command to perform a backup safely
  3. Gzip the file
  4. Uses GPG to encrypt the backup
  5. Send the backup to a locked down bucket on S3 via curl (so no aws cli dependency)
  6. Cleans up when done

On S3, I have the bucket configured to delete any files older than 31 days. This should keep costs in check, and you should configure this to your needs.

Before the script, I want to give a big shout-out to Paweł Urbanek and his guide for doing this with PostgreSQL + Heroku. I have been running a similar setup for a couple of years now, and knowing my data is safe outside of Heroku is excellent. I also want to shout out this Chris Parson's gist, which paved the way for sending the data to S3 without needing to install the ASW CLI.

The script uses five ENV variables (although you can hard code your values at the top)

The one BACKUP_S3_DB_PASSPHRASE must be saved somewhere you will remember. This is the passphrase used by GPG. The only thing worse than losing your database is having a backup you cannot decrypt. 😁

Here is a gist of the script.

#!/bin/bash
set -e

s3_key=$BACKUP_S3_KEY
s3_secret=$BACKUP_S3_SECRET
bucket=$BACKUP_S3_BUCKET
backup_db_passphrase=$BACKUP_S3_DB_PASSPHRASE
data_directory=$SQLITE_DATABASE_DIRECTORY
# ensure each backup has the same date key
date_key=$(date '+%Y-%m-%d-%H-%M-%S')

function backupToS3()
{
  database=$1

  database_file_name=$(basename -- "$database")
  database_name="${database_file_name%.*}"

  backup_file_name="/tmp/$database_name-backup-$date_key.sqlite3"
  gpg_backup_file_name="$database_name-$date_key.gpg"

  sqlite3 "$database" ".backup $backup_file_name"
  gzip "$backup_file_name"
  gpg --yes --batch --passphrase="$backup_db_passphrase" --output "/tmp/$gpg_backup_file_name" -c "$backup_file_name.gz"

  date=$(date +"%a, %d %b %Y %T %z")
  content_type='application/tar+gzip'
  string="PUT\n\n$content_type\n$date\n/$bucket/$gpg_backup_file_name"
  signature=$(echo -en "${string}" | openssl sha1 -hmac "${s3_secret}" -binary | base64)
  curl -X PUT -T "/tmp/$gpg_backup_file_name" \
    -H "Host: $bucket.s3.amazonaws.com" \
    -H "Date: $date" \
    -H "Content-Type: $content_type" \
    -H "Authorization: AWS ${s3_key}:$signature" \
    "https://$bucket.s3.amazonaws.com/$gpg_backup_file_name"

  rm "$backup_file_name.gz"
  rm "/tmp/$gpg_backup_file_name"
}

for file in "$data_directory"/*.sqlite3; do
  backupToS3 "$file"
done

Quick Summary of the script

  1. Lines 4-8 - grab the ENV variables
  2. Line 10 - grab a date we can use to append to the file name and avoid collisions
  3. Line 12, declare a function backuToS3 we will use at the end to iterate over each database in the directory
  4. Lines 14-17 - extract the database file name. A significant benefit to SQLite is there is no harm in having many databases for individual tasks. For HowIVSCode, I use LiteStack, which creates separate databases for Data, Cache, and Queue.
  5. Lines 22-24 - backup, zip, and encrypt
  6. Lines 26-35 - send the file to AW3. If you have the AWS CLI installed, you could probably replace that with aws s3 cp "/tmp/${gpg_backup_file_name}" "s3://$bucket/$gpg_backup_file_name"
  7. Lines 37-38 - clean up the tmp files
  8. Lines 41-43 - loop through any .sqlite3 files in the directory.
#