Skip to content

v1.1

Choose a tag to compare

@github-actions github-actions released this 05 Dec 20:40
e673fb2

v1.1 — the release for the day after launch

1.0 was about writing an app. 1.1 is about running one: behind a load balancer, with a log a machine can read, a key that can be rotated, a scraper that needs numbers, a second instance, and something to tell whoever is on call when a page throws.

It is a minor release under the stability policy. What 1.0 marked stable is unchanged. Everything new is marked provisional in the API reference, and almost all of it does nothing until you ask for it. Every one of the few things you can notice without asking is listed under Upgrading from 1.0, at the end of these notes.

go get github.com/LuigiDavideMicca/borgo@v1.1.0 && go mod tidy
bun add borgo-framework@1.1.0
bun run build

A new app: bunx create-borgo@latest my-app.


At a glance

Operate /readyz and borgo.Ready, a stop that drains, a request id on everything, an access log, JSON logs, metrics you can alert on
Protect session key rotation, borgo.Limit, auth events, password rehash on sign-in, an in-flight cap, a handler timeout, BORGO_HOST, an opener policy, HSTS and Permissions-Policy as settings
Scale out borgo.FanOut and borgo.Deliver, so Push reaches every instance
Forms and APIs BindValid and Invalid, ApiError.fields(), WithSession, Uploads.ServePreview
Pages an error boundary around every page, onClientError and onServerError, production source maps, once() for loaders, head.links and head.lang, focus and an announcement after a client navigation, a safe next page after a deploy
Test borgotest for handlers, borgo-framework/testing for loaders and actions
Verify an independent verifier, mutation tests on the core, every page of the docs read against the code, a new benchmark campaign

Operate it

/readyz, borgo.Ready, and a stop that drains

/healthz says the process is alive, and says so with a 200 whatever else is true. A load balancer needs a status it can act on, and had none; and on a stop signal the listeners closed at once, while the balancer was still sending.

/readyz answers 200 when the render service is reachable and every check the app registered passes, and 503 otherwise:

borgo.Ready("database", func(ctx context.Context) error {
	return db.PingContext(ctx)
})

It names what failed and never why: the reason goes to the log, once when a failure begins and once when it ends. A check runs on every probe and has two seconds to finish. One that hangs or panics is a failure, not a held probe, and the probes that arrive while a check runs share that one run.

BORGO_SHUTDOWN_DELAY is how long the process goes on serving after a stop signal, with /readyz already at 503 — the time a balancer takes to stop sending. Unset, a stop is what it was in 1.0. Behind a balancer, point its health check at /readyz and set the delay to cover its probe interval.

A request id, an access log, logs a machine can read

Every request on the public port has an id now: on the response as X-Request-Id, on the request your handler and the render service see, in borgo.RequestID(r), and on every record borgo.Log(r) writes. A loader's API call carries the id of the page's request, so one page view is one id across both processes.

A proxy borgo trusts may name the request, so the id is the one already in the proxy's log. From anybody else an inbound id is replaced: a caller who chooses the id can write another request's name into your log.

  • BORGO_ACCESS_LOG=1 writes one record per request when it ends: method, path without the query, route, status, bytes, duration, client.
  • BORGO_LOG_FORMAT=json makes every line the Go process writes a JSON object — borgo's and the app's, through log or slog. The render service's own output is not reformatted; onServerError, below, is how that reaches a collector.

Both are refused at boot when the value cannot be read.

Metrics you can alert on

/metrics, which exists when BORGO_METRICS=1, used to say how many requests there had been and how long they took, and nothing about how close the process was to its limits. It now carries the requests in flight, the sockets and streams held against their caps, the handlers that panicked, the sign-ins the limit turned away, the requests the in-flight cap refused, the handlers that ran out of time, the goroutines and the heap — and counters of your own:

var signups = borgo.NewCounter("app_signups_total", "accounts created")

signups.Inc()

It also lists every route of the app, and it used to answer anyone: behind the generated proxy config, that meant the whole internet. A request that came through a trusted proxy now gets a 404, while a scraper that reaches the port itself reads the page as before. BORGO_METRICS_TOKEN asks for a bearer token instead, wherever the request comes from.


Protect it

SESSION_SECRET can be rotated without signing everybody out

One key signed and verified, so a new key invalidated every cookie, and a rotation policy meant a mass logout on a schedule. SESSION_SECRET_PREVIOUS names the keys that signed before, comma-separated. A cookie one of them signed is still read; nothing is signed with them again. Move the current key there, set a new one, and take the old one out when the longest session it signed has run out — or at once, when the key leaked and signing everybody out is the point. A previous key too short to be a key is refused at boot.

borgo.Limit, for your own routes

The docs had a recipe where there was no function:

limited := borgo.Limit(30, time.Minute, borgo.ByClient)

mux.HandleFunc("POST /api/invites", limited(SendInvite))

Past the count, a key gets 429 with Retry-After until its window ends. ByClient counts an IPv6 address by its /64, and so does the built-in sign-in limit now: counted per address, one customer line held as many allowances as it had addresses. The sign-in limit also counts an attempt when it is let in, not after the password has been checked, so a burst of guesses sent together can no longer all be checked.

Hooks for sign-in, sign-out and panics

  • Auth.OnEvent is told of every sign-in, failure, refusal, sign-out and new account: the audit log, the "new sign-in" mail, a lockout of your own.
  • Auth.Rehash: a password hash made with fewer rounds than today's is replaced at sign-in, the one moment the password is known. The default hasher supports it.
  • borgo.OnPanic hands a handler's panic to whatever pages somebody, besides the log line and the 500.
  • borgo.RenewSession writes a session again once it is old enough: a session that lasts while it is used and ends after it is not.

A cap on requests in flight, and a time for a handler to finish in

Both off unless asked for.

  • BORGO_MAX_INFLIGHT is how many API requests are served at once. Past it, a request is answered 503 with Retry-After immediately, instead of joining a queue that makes every request slow and the process large.
  • BORGO_HANDLER_TIMEOUT is how long a handler has. When it passes, the request's context ends with a cause that says why, and a request whose handler wrote nothing is answered 503. A handler that answers late keeps its own answer. One that ignores its context is not stopped, because nothing in Go can stop it.

An event stream is neither counted nor timed, /ws does not come through either, and /healthz and /readyz are outside the cap, so a full server can still say it is alive.

Headers and interfaces

  • BORGO_HOST names the interface the public port listens on. 127.0.0.1 keeps an app that sits behind a proxy on the same machine from also answering on its own port. A value that is not an IP address refuses to start. Unset, nothing changes.
  • Cross-Origin-Opener-Policy: same-origin-allow-popups is on every response. A page opened by another origin gets no handle on your window (window.opener is null), and the popup an OAuth sign-in opens still reaches the page waiting for it.
  • BORGO_HSTS sets Strict-Transport-Security independently of SESSION_SECURE: 0 behind a proxy that sends its own, 1 to send it even though SESSION_SECURE is unset, or the whole value when you can promise includeSubDomains or preload.
  • BORGO_PERMISSIONS_POLICY is sent as written. There is no default on purpose: a guess would turn a camera or a map off in somebody's product.

Scale it out

FanOut and Deliver: Push with more than one instance

The realtime relay lives in the process, so Push reached the sockets of that process and no others. With two instances behind a balancer, half the room heard nothing, and nothing in borgo could be done about it.

borgo.FanOut sets where Push sends an event instead — a bus every instance listens on — and borgo.Deliver is what the listening end calls to hand an event to the sockets of its own process. With a FanOut set, Push delivers nothing itself: the bus brings the event back to every instance, the sender among them. borgo chooses no bus: Redis, NATS, Postgres LISTEN, whatever you already run. An event no socket could carry is refused before it crosses, and a bus that cannot be reached fails the Push instead of telling half the room.

The new guide, more than one instance, covers the rest of what a second instance changes.


Forms and APIs

BindValid and Invalid: one shape for a form that is wrong

Every app with more than a few forms invented its own body for "this field is wrong", and the page reading it had to know which. Invalid is that answer — a map of fields to what is wrong with each — and BindError writes it as 422 {error, fields}.

BindValid is Bind followed by the form's own check, through a Validate() error method on the value or on its pointer. On the other side, ApiError.fields() reads the fields back, and is empty for any other refusal. Bind itself validates nothing, exactly as in 1.0, and borgogen reads BindValid's form as the route's request type.

WithSession: a request the app authenticated its own way

An API that scripts and bots call authenticates with a token in a header, but its handlers are the ones the pages use, and they ask GetSession who is calling. borgo.WithSession(r, v) returns the request as one made by v, for that request alone: no cookie is written, no signature is checked. Found while building bots for piazza.

Uploads.ServePreview: a PDF shown in the page that holds it

Serve hands every file that is not a raster image over as a sandboxed download — right for what a stranger uploaded, and it left no way to show a PDF where it was posted. ServePreview serves a PDF inline and lets a page of the same origin frame it, and nobody else. Every other type goes out exactly as Serve sends it, and the type is the one read from the bytes, so HTML that claims to be a PDF is still a sandboxed download.


Pages

A page that throws keeps its layout

A page that threw while rendering in the browser took the whole tree with it: an empty document and nothing to click. Every page is now rendered inside an error boundary, the same on the server so the two trees have one shape. It shows the page's own ErrorBoundary export, or a plain notice with a way to reload; the layouts stay; and the page is tried again on the next navigation.

  • onClientError is told what the boundary caught, what React recovered from, and what nothing caught.
  • onServerError is told of a failed render, a stream that failed after its first byte, and what the server's own net caught — with the request when there is one. A reporter that throws does not become the error it was told about.
  • borgo build --sourcemap (or BORGO_SOURCEMAP=1) writes production source maps to dist/sourcemaps, under the names their chunks are served by, and never beside the chunks: a map is your source.

once(): what the loaders of a request share

The loaders of a route run side by side and cannot hand each other anything, and they often need the same thing.

import type { LoaderContext } from "borgo-framework";

// in pages/tasks/_layout.tsx
export async function loader({ api, once }: LoaderContext) {
  const { tasks } = await once("tasks", () => api("GET /api/tasks"));
  return { count: (tasks ?? []).length };
}

The page under that layout writes the same line with the same key, and one request reaches the API. It lasts one run of a route's loaders, so it is not a cache, and one visitor's answer is never another's.

head: canonical links, language, and the layouts' data

  • head.links writes a page's canonical address and its versions in other languages. Only the links that relate a page to others, never the ones that make a browser fetch something: head is often built from data, and data should not be able to ask a page to load a file.
  • head.lang puts the page's language on <html>, on the server and after a client navigation.
  • A head function is told what the layouts loaded, as well as the page's own props. A title that names the workspace no longer needs the page to fetch the name for the title alone.

Navigation that a keyboard and a screen reader can follow

After a client navigation the new page's title is announced and focus moves to its heading, as a page load would have done. Before, focus stayed on a link of a page that was gone. A page in which an input already holds the focus is left alone.

A tab open across a deploy

A tab opened before a deploy ran the old components and was handed the new build's data for the next page; whatever the two disagreed on showed as a broken page or a wrong one. The props now say which build made them, and a tab on another build lets the browser load the next page whole.


Test it

Two small packages that let a test say what it is about without building a request or a context by hand.

borgotest, in Go — a request as the generated client sends it, made by whoever the test says, run inside the chain borgo.Serve puts around every route:

func TestOnlyTheOwnerDeletes(t *testing.T) {
	r := borgotest.As(borgotest.Request(t, "DELETE /api/tasks/7", nil), Me{UserID: 2})
	borgotest.SetPath(r, "id", "7")
	borgotest.Do(t, http.HandlerFunc(DeleteTask), r).Status(t, http.StatusForbidden)
}

borgo-framework/testing, in TypeScript — loaderContext and actionContext build what a loader or an action is handed from the few things a test cares about, answer the API routes it calls, fail by name on a route the test did not expect, and keep the calls made:

const context = loaderContext({
  url: "/tasks?done=1",
  session: { userId: 7 },
  api: { "GET /api/tasks": ({ query }) => ({ tasks: [{ id: 1, title: "x", done: query?.done }] }) },
});
const props = await loader(context);

The new guide is testing.


Docs

Besides the two new guides, the recipes gained background work, password reset by mail, calls from another origin, files beyond the local disk, and what a public site owes a search engine: canonical addresses, robots.txt, and a sitemap as a route.


Fixes

  • A range conditioned on a date gets the whole file. An If-Range carrying a date equal to Last-Modified was honoured, and a date is no stronger than the weak tag borgo already refuses there: two encodings of one asset written in the same second share it. Any If-Range on an asset now answers the whole representation, as the docs said.
  • A rewritten address with no page of its own revalidates in place. revalidate(), or a form posted to itself, on such an address was handed to the browser, which loaded the page whole and lost what it held.
  • A page at /readyz is warned about by the build, as one at /healthz already was.
  • create-borgo: a template's module file is gomod until an app is scaffolded. It shipped as a go.mod whose module line was a placeholder, which no tool could parse.

How it was checked

  • An independent verifier, given the properties of the release and not the code, broke six of thirteen before anything shipped. Among them: /metrics read through a proxy by a request with an empty first X-Forwarded-For line; a sign-in limit that counted a failure only after the password was checked, so two hundred guesses sent together were all checked; a readiness check that hangs being started again by every probe; BindValid[*Form] never asking the form. Each one is fixed, and each is kept as the test the verifier wrote, in verified11_test.go.
  • Mutation tests on what guards something. The commits say the counts: seven mutants for the request id and logs, eight for readiness and shutdown, ten for limits and hooks, eleven for the in-flight cap and the timeout — every one either caught by a test, or unable to compile, or shown to be equivalent.
  • The docs, claim by claim. Every page was read against the code, and about forty statements were corrected. The TypeScript and Go snippets in the docs are compiled by bun run check:docs, except the fragments marked as deliberately partial.
  • A second app. 1.1 was written beside piazza, a workspace chat you host yourself, built on borgo. Several of these features exist because piazza needed them.

Benchmarks

There is a new full campaign in bench/results/, the first one committed on the topology borgo has had since 0.30, with the Go binary answering the public port. The benchmark page shows it, with the biases above every number. borgo was measured from the 1.1 source tree before the version bump, so the result file labels it 1.0.0.

Read it for what it is: one laptop, a harness written by the author of one of the subjects, and 11 of 27 comparisons that drifted between the two sweeps by more than their own run-to-run noise (the widest by 7.6%). With that said, the two sweeps measured, in requests per second:

scenario borgo Astro Next.js
JSON, one small object 55,709 / 56,793 4,913 / 5,155 2,814 / 2,815
JSON, a list of about 9 kB 20,827 / 20,878 4,100 / 4,005 2,417 / 2,410
a server-rendered page 4,818 / 4,891 2,727 / 2,934 693 / 680
a static file 8,608 / 8,814 7,708 / 7,459 7,488 / 7,552

The page row is not like for like: borgo's document is 2,230 bytes, Astro's 8,311 and Next.js's 12,025, and a smaller response is less work.

The numbers do not flatter borgo everywhere, and it is better said here. Every plain router in the campaign serves the static file faster than borgo: Elysia and Hono about three and a half times (30,755 / 31,500 and 30,682 / 30,165), Fastify and Express a little under three (24,667 / 24,901 and 22,681 / 22,780). And each open event stream costs borgo 51–52 KiB of memory, against 4–6 KiB for Elysia and Hono (1,000 streams held). The numbers worth quoting are the ones you measure yourself: bun bench/run.ts.


Upgrading from 1.0

No file an app is made of changes, and no environment variable an app already sets changes meaning. The full guide, with a checklist, is upgrading. In short, these are the things you can notice without asking for them:

Code that may stop compiling

  • A LoaderContext built by hand in a test needs once. A loader itself is untouched. loaderContext() from borgo-framework/testing builds one for you.

Behaviour a deployment can run into

  • With BORGO_METRICS=1, /metrics answers 404 to a request that came through a trusted proxy. If your scraper goes through one, or scrapes from an address BORGO_TRUSTED_PROXIES names, set BORGO_METRICS_TOKEN and send it as Authorization: Bearer.
  • The sign-in limit counts an IPv6 address by its /64. Visitors on one IPv6 network now share an allowance; BORGO_LOGIN_ATTEMPTS is the number to raise if that is your audience.
  • Every response carries Cross-Origin-Opener-Policy: same-origin-allow-popups. An app meant to be opened as a popup by other sites, and to answer them through window.opener, sets the header itself on that route, to unsafe-none: a header already on the response is left alone.
  • An inbound X-Request-Id is replaced unless a trusted proxy sent it.
  • /readyz is answered before any page: a page at pages/readyz.tsx is no longer reachable.
  • borgo.Push refuses the event name __count, which is the relay's own.

Behaviour a page can run into

  • A boundary of your own in a layout no longer sees a page's rendering error, because borgo's is nearer to the page. Export ErrorBoundary from the page for what is shown, and register onClientError for what is reported. An end-to-end test that waited for a blank page after a crash waits for [data-borgo-error] instead.
  • The first <h1> (or <main>) is focused after a client navigation and gains tabindex="-1", and a visually hidden #borgo-announcer element sits at the end of <body>: a DOM snapshot will contain both. Code that moved focus itself should be removed or checked; there is no switch.
  • A tab open across a deploy loads its next page whole, so state a layout held in memory is lost with it.

bun run build regenerates the one generated file that changed, .borgo/client.tsx.


Full changelog: v1.0.0...v1.1.0 · Docs: docs/