Skip to content

Design patterns

The patterns below are the load-bearing ideas of the codebase. Each has a why, and a where so you can see it in the code. When you add something, reach for these first: code that follows the existing shapes is easier for the next person (including future you) to read.

Architecture-level patterns

Modular monolith

One binary, many packages with clear boundaries (spec, render, pipeline, controller…). Packages talk through small interfaces, never through shared globals.

  • Why: one Deployment is easy to run on a Pi cluster, one version to reason about, no network calls between components, no distributed transactions. The package boundaries keep it splittable: the worker, controllers and API could become separate Deployments by changing only cmd/rendimiento/main.go (see Scaling).
  • Where: cmd/rendimiento/main.go wires everything.

Composition root / dependency injection by hand

main.go reads settings, builds every concrete object (store, GitHub holder, DNS provider, executor, runner, platform, controllers, API server) and passes each one what it needs through struct fields.

    ns := env("NAMESPACE", "rendimiento-system")
    dsn := os.Getenv("DATABASE_URL")
    if dsn == "" {
        return errors.New("DATABASE_URL is required")
    }
    // ALLOWED_USERS names the first administrators; then people are
    // members, managed on the Members page.
    users := strings.FieldsFunc(os.Getenv("ALLOWED_USERS"), func(r rune) bool { return r == ',' || r == ' ' })

    st, err := store.Open(ctx, dsn)
    if err != nil {
        return fmt.Errorf("database: %w", err)
    }
    defer st.Close()
    if err := st.Migrate(ctx); err != nil {
        return fmt.Errorf("migrate: %w", err)
    }
    // The settings tested and changed on the Environment page (Keys and
    // settings) win over the ConfigMap's: they go into the environment
    // before anything reads it. TESTED_SETTINGS=ignore starts with the
    // ConfigMap's alone.
    entorno, probadosEnUso, err := probados.AlArrancar(ctx, st, os.Getenv, os.Setenv)
    if err != nil {
        log.Warn("could not read the tested settings; starting with the ConfigMap's", "err", err)
        for k, v := range entorno {
            _ = os.Setenv(k, v)
        }
    } else if len(probadosEnUso) > 0 {
        log.Info("tested settings changed on the Environment page win over the ConfigMap's", "settings", strings.Join(probadosEnUso, ", "))
    }
    baseURL := strings.TrimRight(env("BASE_URL", "http://localhost:8080"), "/")
    go central.Run(ctx, st, plain)
    // The Problems recorder's own warnings are kept in the log.
    go problemLog.Run(ctx, st, slog.New(central.Handler(plain.Handler())))
    if n, err := st.SeedAdmins(ctx, users); err != nil {
        return fmt.Errorf("members: %w", err)
    } else if n > 0 {
        log.Info("the first administrators come from ALLOWED_USERS; from now on, manage people on the Members page", "admins", n)
    }
    if ms, err := st.Members(ctx, store.DefaultOrg); err != nil {
        return fmt.Errorf("members: %w", err)
    } else if len(ms) == 0 {
        // The setup page makes the first administrator: whoever proves the
        // setup token and authorizes the forja (internal/api/instalar.go).
        if os.Getenv("SETUP_TOKEN") == "" {
            return errors.New("nobody can sign in: set ALLOWED_USERS to the first administrators (ana on GitHub, [email protected], [email protected]), or SETUP_TOKEN to install from the setup page")
        }
        log.Info("no administrators yet: whoever installs from the setup page, with the setup token, becomes the first")
    }
  • Why: no DI framework, no hidden magic. Reading main.go top to bottom tells you exactly what runs and with what. Tests build the same structs with fakes.

Reconciliation loop (level-triggered control)

Controllers don't react to what happened; they compare what should be (the App or Addon spec) with what is (the cluster) and act to close the gap. Every event just means "look again".

// Reconcile brings one app's objects in line with its App object, or cleans up after it is deleted.
func (r *AppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var app v1alpha1.App
    if err := r.Get(ctx, req.NamespacedName, &app); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    if !app.DeletionTimestamp.IsZero() {
        return ctrl.Result{}, r.finalize(ctx, &app)
    }
    if controllerutil.AddFinalizer(&app, finalizer) {
        if err := r.Update(ctx, &app); err != nil {
            return ctrl.Result{}, err
        }
    }

    status := v1alpha1.AppStatus{ObservedGeneration: app.Generation, Release: app.Status.Release}
    result, err := r.sync(ctx, &app, &status)
    if err != nil {
        status.Phase, status.Message = v1alpha1.PhaseError, err.Error()
        log.FromContext(ctx).Error(err, "sync failed")
    }
    app.Status = status
    if uerr := r.Status().Update(ctx, &app); uerr != nil {
        return ctrl.Result{}, uerr
    }
    if err != nil && !errors.Is(err, errBlocked) {
        return ctrl.Result{}, err // retried with backoff
    }
    return result, nil
}
  • Why: it's self-healing. Missed events, crashes, a person running kubectl delete: the next reconcile fixes it. It's also idempotent: running twice does no harm.
  • Where: AppReconciler.Reconcile, AddonReconciler.Reconcile, and in spirit the add-on git syncer and the DDNS loop (periodic "make it so").

Declarative desired state + server-side apply

The controller computes the complete desired objects (render.Render) and hands them to Kubernetes with server-side apply under the field manager rendimiento. Kubernetes merges, tracks field ownership, and reports conflicts.

  • Why: no read-modify-write races, no diffing by hand; fields other controllers own (HPA replicas, cert-manager annotations) are left alone.

Pure core, imperative shell

spec, detect, generate, render, pipeline.Plan, addon.Render are pure: input in, output out, no cluster, no network. The shell (controllers, executor, API handlers) does I/O and calls into them.

  • Why: the pure parts hold the tricky logic and are tested with fast unit and golden tests. The shell is thin and tested with envtest.

Work queue in the database (transactional outbox-ish)

Runs are rows. Workers claim one with SELECT … FOR UPDATE SKIP LOCKED:

// ClaimRun takes the next queued run (in ClaimRunFor's order), of an app not
// in skip (those with a run going), and marks it running. It returns ErrNotFound when there is
// none. Safe across replicas.
func (s *Store) ClaimRun(ctx context.Context, skip []int64) (*Run, error) {
    return s.ClaimRunFor(ctx, Busy{Full: skip})
}

// Busy is what the runs going rule out for the next one: apps that have as
// many runs going as they may (Full), apps with a deploying run going
// (Deploying: their next deploy waits, so releases keep their order), and
// branches with a run going ("<app id>:<branch>", so a branch's runs keep
// theirs).
type Busy struct {
    Full      []int64
    Deploying []int64
    Branches  []string
}

// branchAging is how long a branch's run waits in the queue before it counts
// as a deploy: deploys of the main branch go first, but a branch is not left
// behind them forever.
const branchAging = 30 * time.Minute

// ClaimRunFor takes the next queued run that b does not rule out, and marks
// it running (ErrNotFound when there is none). Deploys go first, and branch
// runs queued longer than branchAging with them; among those, and among the
// rest, the oldest first.
func (s *Store) ClaimRunFor(ctx context.Context, b Busy) (*Run, error) {
    for _, l := range []*[]int64{&b.Full, &b.Deploying} {
        if *l == nil {
            *l = []int64{}
        }
    }
    if b.Branches == nil {
        b.Branches = []string{}
    }
    return scanRun(s.pool.QueryRow(ctx, `
        UPDATE runs SET status = 'running', started_at = now()
        WHERE id = (SELECT id FROM runs WHERE status = 'queued' AND NOT (app_id = ANY($1))
            AND NOT (deploy AND app_id = ANY($2)) AND NOT ((app_id::text || ':' || branch) = ANY($3))
            ORDER BY (deploy OR created_at < now() - make_interval(secs => $4::float8)) DESC, id
            FOR UPDATE SKIP LOCKED LIMIT 1)
        RETURNING `+runCols, b.Full, b.Deploying, b.Branches, branchAging.Seconds()))
}
  • Why: Postgres is already there; no Redis/RabbitMQ to run. SKIP LOCKED lets many workers claim different rows without blocking each other, and a crash leaves the row claimable again (RequeueOrphans at startup).
  • One deploy per app: PARALLEL_RUNS workers (3) claim side by side. Each skips an app with RUNS_PER_APP runs going (2), a deploy when the app has one going, and a branch with a run going, so one app's long build never holds up another's page, its branches don't wait for each other, and its releases keep their order.

GitOps for configuration, database for releases

The configuration of an app lives in its repo (rendimiento.yaml), add-ons in example/gitops. The release pointer (which image digest runs) lives in the App object and the releases table.

  • Why: config gets code review and history; releases don't create [skip ci] commit noise, and rollback is instant (repoint to an older digest).

Code-level patterns

Small interfaces, defined by the consumer

platform.GitHub, pipeline.Executor, dns.Provider, addon.GitFetcher, generate.Generator. Each declares only the methods its user calls. Real implementations and test fakes both satisfy them. See Go for this codebase.

Strategy

A family of interchangeable algorithms behind one interface, chosen at startup or per call:

Decision Strategies
How to build an image Dockerfile vs Railpack (build.builder)
Which DNS provider Cloudflare vs Noop
How an add-on renders Helm chart vs kustomize/plain manifests
Which BuildKit daemon pool (rendezvous hash) vs a single address

Adapter

github.Holder adapts the GitHub REST API to platform.GitHub; GitHubFetcher adapts a repo tree to fs.FS so Helm and kustomize can read it like a local folder; the log recorder adapts Kubernetes log streams to io.Writer + the store + SSE.

Holder (atomic swap)

The GitHub App credentials don't exist until setup finishes. github.Holder wraps an atomic.Pointer so the running server can swap in a configured App without a restart, and every caller sees either "not configured" or a complete App, never half of one.

Observer / publish-subscribe

events.Hub fans out change notifications (run updated, app status changed) to every browser connected over Server-Sent Events. Producers call Publish and don't know who listens.

Builder-free options with defaults

Specs and settings are plain structs; a Default() method fills gaps and Validate() checks the result, reporting every problem at once (errors.Join). No builder chains, no functional options: the YAML is the options.

Template method (pipelines)

pipeline.Plan turns a spec into a DAG of steps (clone → test → build per service). The runner walks any DAG the same way; only the steps differ. New step kinds plug in without touching the runner (see Recipes).

Rendezvous hashing

buildkitFor chooses a BuildKit daemon for an image by hashing (image, daemon) and taking the highest score:

// buildkitFor picks the pool daemon for key by rendezvous hashing with
// bounded loads (Mirrokni, Thorup and Zadimoghaddam, SODA 2018): the ready
// daemons are ranked by their hash with the key, as each key's stable
// favourite first, and the build goes to the first one with fewer builds
// than its share (cargaTope). Only the keys of a daemon that goes away move
// elsewhere, and two builds at once do not pile on one daemon while another
// is idle. Daemons on nodes that take no runs (BUILD_EXCLUDE_NODES, the
// Environment page's Capacity) are left out while another is there: an
// image then builds elsewhere, with the cache it keeps in the registry. It
// returns the address, the daemon's name and soltar, which the caller
// defers: it gives the daemon's place back when the build ends. Without a
// pool it returns the single BuildkitAddr, "" and a soltar that does
// nothing.
func (k *KubeExecutor) buildkitFor(ctx context.Context, key string) (string, string, func()) {
    nada := func() {}
    if k.BuildkitPool == "" {
        return k.BuildkitAddr, "", nada
    }
    res := k.Resolver
    if res == nil {
        res = net.DefaultResolver
    }
    lctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()
    _, srvs, err := res.LookupSRV(lctx, "buildkit", "tcp", k.BuildkitPool)
    if err != nil || len(srvs) == 0 {
        return k.BuildkitAddr, "", nada
    }
    // The daemons on nodes of another architecture (a node «a ratos») build
    // only an image's other half (buildkitOtro).
    var propios []*net.SRV
    for _, s := range srvs {
        if k.deArch(ctx, s.Target, archPrincipal) && !k.sinCI(ctx, s.Target) {
            propios = append(propios, s)
        }
    }
    if len(propios) == 0 {
        return k.BuildkitAddr, "", nada
    }
    srvs = propios
    if off := k.avoided(); len(off) > 0 {
        var on []*net.SRV
        for _, s := range srvs {
            if !slices.Contains(off, k.daemonNode(ctx, s.Target)) {
                on = append(on, s)
            }
        }
        if len(on) > 0 {
            srvs = on
        }
    }
    hosts := make([]string, len(srvs))
    for i, s := range srvs {
        hosts[i] = strings.TrimSuffix(s.Target, ".")
    }
    k.cargaMu.Lock()
    if k.carga == nil {
        k.carga = map[string]int{}
    }
    i := escogerAcotado(hosts, key, k.carga)
    host := hosts[i]
    k.carga[host]++
    k.cargaMu.Unlock()
    var una sync.Once
    soltar := func() {
        una.Do(func() {
            k.cargaMu.Lock()
            defer k.cargaMu.Unlock()
            if k.carga[host]--; k.carga[host] <= 0 {
                delete(k.carga, host)
            }
        })
    }
    daemon, _, _ := strings.Cut(host, ".")
    return fmt.Sprintf("tcp://%s:%d", host, srvs[i].Port), daemon, soltar
}

// cargaHolgura is c in the bounded loads: a daemon takes a build while it
// has fewer than ⌈c × the average⌉, c = cargaNum/cargaDen = 1.25. Larger
// keeps more images on their favourite (warm cache), smaller spreads them
// more evenly.
const cargaNum, cargaDen = 5, 4

// cargaTope is how many builds a daemon may have before it takes another:
// ⌈c·activos/D⌉ with the builds active now (not counting the new one), and
// at least 1. Counting before the new one is the adjustment for few builds:
// with c = 1.25 and 2 to 5 daemons, each takes one before any takes a
// second (3 builds on 3 daemons included), and a daemon still never has
// more than ⌈c·N/D⌉ of N builds.
func cargaTope(activos, d int) int {
    t := (cargaNum*activos + cargaDen*d - 1) / (cargaDen * d)
    return max(t, 1)
}

// hrw is a daemon's rendezvous score for key (FNV-1a 64 of "daemon|key").
func hrw(host, key string) uint64 {
    h := fnv.New64a()
    h.Write([]byte(host + "|" + key))
    return h.Sum64()
}

// escogerAcotado is the index of the host key goes to: the first, by
// rendezvous score, with fewer builds in carga than cargaTope. Without load
// it is the host of the highest score, key's favourite.
func escogerAcotado(hosts []string, key string, carga map[string]int) int {
    orden := make([]int, len(hosts))
    punto := make([]uint64, len(hosts))
    activos := 0
    for i, h := range hosts {
        orden[i], punto[i] = i, hrw(h, key)
        activos += carga[h]
    }
    sort.SliceStable(orden, func(a, b int) bool { return punto[orden[a]] > punto[orden[b]] })
    tope := cargaTope(activos, len(hosts))
    for _, i := range orden {
        if carga[hosts[i]] < tope {
            return i
        }
    }
    // Not reached: D·tope > activos, so one has room. The favourite, then.
    return orden[0]
}
  • Why: the same image always lands on the same daemon (warm cache), and adding/removing a daemon only moves the images that hashed to it. No coordinator needed.
  • Bounded loads: a favourite already busy passes the build to the next daemon in the image's order once it has its share (⌈1.25 × the average⌉), counted in memory and given back with defer soltar().

Ownership and labels as the index

Everything rendimiento creates carries app.kubernetes.io/managed-by: rendimiento and rendimiento.ai/app (or rendimiento.ai/addon) labels, and owner references where possible. Pruning is "list by label, delete what isn't desired"; adoption is "take over objects that match but lack our labels, only after a human agrees".

Safety gates

Destructive or surprising changes stop and ask: adoption of existing objects, add-ons with manualSync, neverDelete kinds (CRDs, Namespaces, PVCs, PVs, StorageClasses), the pause annotation, pre-delete hooks. The controller returns errBlocked and shows why in status, rather than guessing.

Sentinel errors and wrapped errors

store.ErrNotFound, errBlocked, and fmt.Errorf("…: %w", err) everywhere. Callers branch on kinds of failure with errors.Is.

Embed everything

UI, templates and migrations are //go:embed-ed. The image is one static binary; a deploy can never mix a new binary with old assets.

Patterns deliberately not used

Not used Why not (yet)
ORM Plain SQL with pgx is shorter, faster, and every query is visible.
Message broker The Postgres queue is enough at this scale; see Scaling.
Microservices One person, one cluster: the operational cost would dwarf the benefit. The boundaries exist to split later.
Plugin loading (plugin package, WASM) Extension points today are interfaces compiled in; the plugin contract (containers, JSON in/out) is on the roadmap.
Global loggers/config Everything is passed explicitly, so tests can run in parallel.