Tuesday, May 26, 2020

Creating a Database Enum in Vapor 4

Vapor has essentially become the web framework for the Swift programming language so I’ve been doing quite a bit of experimenting with it. Unfortunately, the documentation for the latest version is still rather incomplete as of this writing. As such, I thought I would add to the general body of knowledge about Vapor available on the web.

For a project I’ve started working on, I wanted to add an enumerated type (more commonly known simply as an ENUM) to my PostgreSQL database, use that ENUM as the type on a column on one of my tables, and have a default value. The first thing, then, was to define the ENUM itself in Swift:

Sources/App/Models/Account.swift

enum BillingStatus: String, Codable {
    case current
    case pastDue
}

Then I could define a model that uses the ENUM:

Sources/App/Models/Account.swift

final class Account: Model {
    static let schema = "accounts"

    @ID(key: .id)
    var id: UUID?

    @Enum(key: "billing_status")
    var billingStatus: BillingStatus

    init() {}

    init(
        id: IDValue? = nil,
        billingStatus: BillingStatus = .current
    ) {
        self.id = id
        self.billingStatus = status
    }
}

Lastly, I needed to define the migration code. This is a little more tricky that you might at first suppose for two reasons: (1) the ENUM type must be created before it can be used as a column type on the table, and (2) Vapor 4’s migrations are asynchronous, so extra steps are needed to ensure a consistent order of operations. To handle this situation, I used flatMap to provide a callback block that will execute as soon as the ENUM definition block has finished. The inverse must be also done in the revert method.

Sources/App/Migrations/CreateAccount.swift

import Fluent

struct CreateAccount: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        return database.enum("billing_status")
            .case("current")
            .case("past_due")
            .create()
            .flatMap { billing_status in
                return database.schema("accounts")
                    .id()
                    .field(
                        "billing_status",
                        billing_status,
                        .required,
                        .custom("DEFAULT 'current'")
                    )
                    .create()
            }
    }

    func revert(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("accounts").delete().flatMap {
            return database.enum("billing_status").delete()
        }
    }
}

I used Vapor’s .custom method to specify that current is the default, mirroring the default used in the model code’s init method. You may well feel that specifying a default in both the database and the application layers is redundant but I prefer to keep the two in sync where feasible.

All code tested with Swift 5.2, Vapor 4.5, and Fluent 4.0.0-rc2.2 on both macOS 10.15 and Ubuntu Linux 18.04.


Sunday, May 17, 2020

“Second-Guessing the Modern Web” ↦

Tom MacWright writing on his blog:

The emerging norm for web development is to build a React single-page application, with server rendering. The two key elements of this architecture are something like:

  1. The main UI is built & updated in JavaScript using React or something similar.
  2. The backend is an API that that application makes requests against.

This idea has really swept the internet. It started with a few major popular websites and has crept into corners like marketing sites and blogs.

I’m increasingly skeptical of it.

I’ve always been skeptical of it but it is very interesting to read this from the perspective of someone who had embraced React more fully than I had. Mr. MacWright has worked on the front-end for both Mapbox Studio and Observable, both of which are largely implemented in React.

Mr. MacWright identifies four areas where single-page applications (SPAs) have settled on some “messy optimizations” for frequently-encountered problems with SPAs:

  1. Bundle splitting
  2. Server-side rendering
  3. APIs
  4. Data fetching

But I’m at the point where I look at where the field is and what the alternative patterns are — taking a second look at unloved, unpopular, uncool things like Django, Rails, Laravel — and think what the heck is happening. We’re layering optimizations upon optimizations in order to get the SPA-like pattern to fit every use case, and I’m not sure that it is, well, worth it.

[...]

But the cultural tides are strong. Building a company on Django in 2020 seems like the equivalent of driving a PT Cruiser and blasting Faith Hill’s “Breathe” on a CD while your friends are listening to The Weeknd in their Teslas. Swimming against this current isn’t easy, and not in a trendy contrarian way.

I’m old enough to remember when frameworks like Django and Ruby on Rails felt cutting-edge but they have both now become boring, stable projects. Is it such a bad thing, though, to build on such a tried-and-true foundation?


Friday, May 8, 2020

DOJ Moves to Drop Charges Against Michael Flynn ↦

Spencer S. Hsu, Devlin Barrett, and Matt Zapotosky reporting for The Washington Post:

The Justice Department moved Thursday to drop charges against President Trump’s former national security adviser Michael Flynn, a stunning reversal that prompted fresh accusations from law enforcement officials and Democrats that the criminal justice system was caving to political pressure from the administration.

[...]

Shortly before the Justice Department abandoned Flynn’s prosecution, the line prosecutor on the case, Brandon Van Grack, formally withdrew — just as the Stone prosecutors had.

In the new filing, Timothy Shea, the U.S. attorney for the District of Columbia, wrote that “continued prosecution of this case would not serve the interests of justice,” but current and former law enforcement officials said the decision was a betrayal of long-standing Justice Department principles. Shea, who was tapped by Barr to lead the U.S. attorney’s office, was the only lawyer to sign the filing; no career attorneys affixed their names to it.

It’s quite telling that the motion to dismiss was signed by a political appointee and not by any of the career attorneys who had been working the case previously. This is obviously a political decision to appease President Trump and the lies about a “lack of a legitimate investigative basis for the interview of Mr. Flynn” are a particularly flimsy excuse.

Under Attorney General William Barr, the Department of Justice has abandoned the pursuit of impartial justice and has instead devolved into an extension of Trump’s misguided will.


Thursday, May 7, 2020

Trump Doubles Down on Ending Obamacare ↦

Devlin Barrett reporting for The Washington Post:

“We want to terminate health care under Obamacare,” Trump told reporters Wednesday, the last day for his administration to change its position in a Supreme Court case challenging the law. “Obamacare, we run it really well. . . . But running it great, it’s still lousy health care.”

While the president has said he will preserve some of the Affordable Care Act’s most popular provisions, including guaranteed coverage for preexisting medical conditions, he has not offered a plan to do so, and his administration’s legal position seeks to end all parts of the law, including those provisions.

The comments are related to a case now scheduled to be argued in front of the Supreme Court which seeks to invalidate the entirety of the Affordable Care Act, commonly referred to as Obamacare. The Court is unlikely to issue a ruling on the case before the November election.

The latest ACA suit was organized by Republican attorneys general in Texas and other states. When the Trump administration declined to defend the law, a coalition of Democratic-led states entered.

The case began after the Republican-led Congress in 2017, unable to secure the votes to abolish the law, reduced to zero the penalty for a person not buying health insurance. Lawyers for the state of Texas argued that in doing so, Congress had removed the essential tax element that the Supreme Court had previously ruled made the program constitutional.

A district judge in Texas agreed and said the entire law must fall. Eventually the Trump administration agreed with that assessment.

In the middle of a pandemic, Trump wants to kill health care coverage for millions of Americans. The previous efforts to repeal Obamacare were so toxic, the Republicans in Congress couldn’t pass a bill to do it in spite of being the majority in both houses during Trump’s first two years as President. Now they are asking the courts to do what they couldn’t. If it wasn’t already accompanied by a deluge of inhumanity from this Administration, it would be breathtakingly cruel.


Thursday, May 7, 2020

Trump Demotes Government Scientist for Raising Alarm ↦

Ricardo Alonso-Zaldivar, Michael Balsamo, and Colleen Long reporting for the Associated Press:

Dr. Rick Bright, former director of the Biomedical Advanced Research and Development Authority, alleges he was reassigned to a lesser role because he resisted political pressure to allow widespread use of hydroxychloroquine, a malaria drug pushed by President Donald Trump. [...]

“I witnessed government leadership rushing blindly into a potentially dangerous situation by bringing in a non-FDA approved chloroquine from Pakistan and India, from facilities that had never been approved by the FDA,” Bright said Tuesday on a call with reporters. “Their eagerness to push blindly forward without sufficient data to put this drug into the hands of Americans was alarming to me and my fellow scientists.”

Dr. Bright further alleges that his attempts to spur action early on met with resistance from Trump Administration officials, including Health and Human Services Secretary Alex Azar and Assistant Secretary for Preparedness and Response Robert Kadlec. Specific efforts to acquire N95 respirator masks as early as January and February were ignored. He also alleges that there pressure to award contracts to the well-connected:

“Time after time I was pressured to ignore or dismiss expert scientific recommendations and instead to award lucrative contracts based on political connections,” Bright said in the call with reporters. “In other words, I was pressured to let politics and cronyism drive decisions over the opinions of the best scientists we have in government.”

So often, underneath the lies and incompetence constantly coming from the Trump Administration, we also find grift. He is without a doubt the most corrupt President of the modern era and very likely ever.


Thursday, May 7, 2020

Amazon VP Resigns over Whistleblower Firings ↦

Kate Cox reporting for Ars Technica:

Amazon VP Tim Bray, who had been with the company for more than five years, has resigned in protest of Amazon’s treatment of warehouse workers and the firing of other employees who spoke out.

The company fired multiple warehouse and office workers in recent weeks amid organizing efforts to improve conditions in the company’s distribution centers, where individuals have contracted COVID-19. Firing the whistleblowers is “evidence of a vein of toxicity running through the company culture,” Bray said in a blog post explaining his departure. “I choose neither to serve nor drink that poison.”

It’s quite rare for an executive to resign over worker treatment and even more rare to do so publicly. I feel that Tim Bray made the right move here.


Thursday, May 7, 2020

A Trinary Star System with a Black Hole ↦

Jennifer Ouellette reporting for Ars Technica (emphasis added):

The [European Southern Observatory (ESO)] team had been conducting a study of double-star systems, and HR 6819 was included as part of their observational data-gathering since it appeared to be just such a system. But while reviewing their data, the astronomers found clear evidence of an unexpected third object in the system: a black hole that had previously eluded detection.

This black hole is the closest ever found at only 1,000 light years away. It’s also relatively small — 4 solar masses compared to an estimated 4.28±0.1 million solar masses for the black hole at the center of our galaxy. The proximity of this black hole suggests that these smaller black holes may be quite common throughout the Universe. And more specifically, these previously-unknown trinary-with-a-black-hole systems may be somewhat common as well:

“If such a system happens to be in the immediate neighborhood, it is likely common in other regions of the galaxy as well,” said Rivinius. His back-of-the-envelope calculation suggests that there could be 2,500 such systems. That’s not going to clear up the large discrepancy between the black holes we’ve discovered and the number astronomers believe could be out there. “But considering so far we were not aware any such triple could exist, it is quite a step,” he added. The ESO team has already identified a second star system that might also be a trinary with a black hole, although more observational data is needed to confirm this.


Thursday, May 7, 2020

Swift Supports New Linux Distributions ↦

The Swift open source project recently announced that they are now officially supporting some Linux distributions other than Ubuntu:

It is my pleasure to announce a new set of Linux distributions officially supported by the Swift project. Swift.org now offers downloadable toolchain and Docker images for the following new Linux distributions:

  • Ubuntu 20.04
  • CentOS 8
  • Amazon Linux 2

The above are added to the Linux platforms we already supported:

  • Ubuntu 16.04
  • Ubuntu 18.04

To include Ubuntu 20.04 in a list of newly supported distributions when versions 16.04 and 18.04 were already supported is a bit of a stretch but it is at least fairly quick turnaround1. The support of CentOS and Amazon Linux are nevertheless most welcome.

I can’t help but point out, however, that Swift’s support of Linux remains... quirky. The downloads for all of these platforms comes in the form of a .tar.gz file that must be manually verified, expanded, resulting files moved into a desirable location in the filesystem, and added to the PATH. Why aren’t they at least offering packages (.deb for Ubuntu and .rpm for CentOS and Amazon Linux)? Where is the PPA for Ubuntu to enable apt install commands? To say nothing of persuading the distributions to themselves include Swift as they do with other languages like Python, Ruby, Go, Rust, etc.

Still, this is progress.


  1. Ubuntu 18.04 wasn’t supported until several months after it was released. 20.04 is being supported within a week or two of its release. 


Wednesday, January 29, 2020

Stuffing a Universe Onto a Single CD‑ROM ↦

Lee Hutchinson from Ars Technica recently interviewed Rand Miller about the creation of the seminal ’90s video game Myst:

Originally available only for Macintosh computers, I had to play Myst at a friend’s house as my parent’s computer was a PC. I was immediately captivated by the surreal world created by Rand and his brother Robyn. Myst has been regularly re-released, including for iOS, so now my children have played it, too.

If you were into computers in the ’90s, and possibly even if you weren’t, you’ll thoroughly enjoy this interview.


Friday, January 24, 2020

Jay Sekulow Is the Blue-Haired Lawyer From the Simpsons

So, in case you haven’t heard, President Trump has been impeached by the House of Representatives and that impeachment is now being tried in the Senate. It’s a very serious matter, even if Mitch McConnell treats it very unseriously.

But speaking of unserious, can we just pause for a moment to reflect on something quite remarkable? One of Trump’s personal lawyers participating in his defense in the Senate is Jay Sekulow. Jay Sekulow, it turns out, bears a remarkable resemblance to the ubiquitous but anonymous blue-haired lawyer in the long-running animated series The Simpsons:

Comparing Jay Sekulow to Simpsons Lawyer

Apropos of nothing, but funny nonetheless.