onair

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 8 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

onair

Green is not Live.

See which commit each service of a deploy is actually running.

Go Version


onair compares three tiers for one environment. HEAD is the latest commit on the branch. Green is the latest commit whose pipeline passed. Live is what each running component says it runs. A stalled deploy, a rollback or a restart loop shows up as the gap between them.

  shop · prod                                  gitlab.com/acme/shop

  HEAD    a1b2c3d (2h ago) by Alice
  → Fix the checkout total • ↗ !1234

  Green   a1b2c3d (2h ago) by Alice  ★ == HEAD
  → Fix the checkout total • ↗ !1234

  Live    9e8d7c6 (3h ago) by Bob  ↓ 1 behind green · 1 behind main · ✓ yours
    backend 9e8d7c6 · worker 9e8d7c6 ✗ restarting (reported)   ✗ worker not serving
  → Add the widget API • ↗ !1230

When every tier agrees, the report collapses to one line:

  Deployed: a1b2c3d (2h ago) by Alice  ★ current
  → Fix the checkout total • ↗ !1234

It is the Go sibling of onair-cli, which does the same for a single Heroku app by reading its slug. Here a deploy is a list of components, such as backend, web and worker, and the forge is GitLab. There is no slug, so each component needs a live source.

Install

go install github.com/amberpixels/onair/cmd/onair@latest

Quick Start

# .onair.yml is found upward from the working directory, like git's root
cat > .onair.yml <<'EOF'
forge: { repo: acme/shop }
environments:
  prod:
    components:
      - name: backend
        live: { probe: "https://shop.example/api/-/version" }
      - name: worker
        live: { command: "ssh prod onair-live shop worker" }
EOF

export GITLAB_TOKEN=...      # read_api; not needed for a public project
onair                        # the only environment, rendered for the terminal
onair -env prod -json        # the same Report as JSON

Live Sources

Each component takes one live: source. The report labels how much it knows, from strongest to weakest:

Source Config Confidence
A /-/version endpoint returning {"commit","builtAt"} probe: <url> probed
A shell command printing a SHA, a tag, an image ref, or {"commit","builtAt","state"} command: <cmd> reported
The newest successful GitLab deployment of an environment environment: <name> recorded
None: Green stands in live: {}, or no source at all assumed
  • command is the universal adapter: ssh + docker inspect, kubectl, flyctl. A state other than running or healthy marks the component as not serving.
  • environment also shows a newer deploy still running (⟳ deploying) or failed (✗ deploy of <sha> failed). It needs only read access to the project, so it works for people who cannot reach the hosts. Set it once on the environment to apply it to every component without a source of its own.
  • Docker Compose hosts: stamp the commit into the image with the OCI label org.opencontainers.image.revision, and contrib/compose-live reads it on the host as a command source. No app code, so it works for workers too.

Usage

onair [flags]
Flag Meaning
-env <name> environment to show; required when more than one is configured
-json print the Report as JSON instead of the terminal view
-branch <name> override the tracked branch
-live-ref <ref> use this commit-ish as Live; - reads it from stdin
-component <name> the component -live-ref applies to (default: the only one)
-config <path> path to .onair.yml
-timeout <d> overall deadline (default 15s)
-no-color disable colors

-live-ref - takes the same output as a command source, so a CI job can pipe it in: ssh prod onair-live shop worker | onair -live-ref - -component worker.

Configuration

project: shop                # default: the repo's last path segment
forge:
  kind: gitlab               # the only forge so far
  repo: acme/shop
  branch: main               # default main
  base_url: https://gitlab.example   # default gitlab.com
  token_env: GITLAB_TOKEN    # the variable holding the token (default)
attribution: auto            # off | on | auto: mark commits as "✓ yours"
identities:
  bob: [bob@example.com, bob@work.example]
task:                        # link tracker ids found in commit subjects
  pattern: 'PROJ-\d+'
  url: https://tracker.example/{id}
environments:
  prod:
    components:
      - name: backend
        live: { probe: "https://shop.example/api/-/version" }
      - name: worker
        live: { command: "ssh prod onair-live shop worker" }
  staging:
    environment: staging     # GitLab deployments are Live for every component below
    components:
      - name: backend
      - name: web
        live: {}             # opt out: Assumed = Green

attribution: auto marks your commits only when your git config user.email, or one of its aliases under identities, authored recent commits on the branch.

As a Library

The CLI only turns the config and flags into providers and renders the result. A host app, such as an admin panel or a status page, imports the core instead. It wires its own providers and renders the Report itself:

report, err := onair.Collect(ctx, onair.Params{
    Forge:      gitlab.NewClient("", "acme/shop", token),
    Branch:     "main",
    Components: []onair.Component{
        {Name: "backend", Live: &live.Probe{URL: "https://shop.example/api/-/version"}},
    },
    Identity:    viewer,                // who is looking, for "yours"
    Attribution: onair.AttributionAuto,
})

The JSON shape of Report is a public API and only changes additively.

How It Works

onair is read-only: it calls the GitLab API, runs your command sources and git config user.email, and never deploys or writes anything. A failing source never stops the report. That component falls back to Green, labeled as assumed, and the error is printed as a note.

A few decisions shape the rest:

  • Green is not Live. They match only when every deploy ships the latest green commit and nothing stalls or rolls back. So Live is its own tier, and Green stands in for it only with an assumed label.
  • Confidence is a field, not a flag. Every Live answer says how it is known, so the report never claims more than its weakest source.
  • No per-platform adapters. command turns any CLI into a live source (contract). Deployment records are a forge feature, like pipelines, so they are the one built-in source besides the probe.
  • Rendering is the host's job. The core returns a Report, and the terminal view and the JSON are two renderers of it.
  • GitLab first, not GitLab only. The forge is an interface, so GitHub can be added without touching the core.

License

MIT © amberpixels

Documentation

Overview

Package onair answers one question - which commit is actually running - by comparing three truth tiers: HEAD (latest commit on the tracked branch), Green (latest commit whose CI pipeline passed) and Live (what the running artifact reports about itself).

The core is pure: it asks abstract questions through three seams - Forge (git + CI truth), LiveProvider (what is running, per component) and Identity (who is viewing, for attribution) - and returns a Report. Rendering lives in package render, concrete providers in packages gitlab and live, and wiring in cmd/onair. Host applications import this package directly, wire their own providers and render the Report however they like.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LooksLikeSHA

func LooksLikeSHA(s string) bool

LooksLikeSHA reports whether s has the shape of a full or abbreviated commit SHA (7 to 40 hex characters), as opposed to a tag or an image ref.

func SameSHA

func SameSHA(a, b string) bool

SameSHA reports whether two SHAs name the same commit, tolerating abbreviated forms: a probe typically reports a short SHA while a forge returns the full one. Anything shorter than 7 hex characters must match exactly - prefixes that short are not trustworthy.

func Serving

func Serving(state string) bool

Serving reports whether a provider-reported state means the component serves traffic. An unknown (empty) state counts as serving, so providers that report no state render as before.

func ShortSHA

func ShortSHA(sha string) string

ShortSHA abbreviates a SHA for display.

Types

type AttributionMode

type AttributionMode string

AttributionMode gates the "yours" annotations.

const (
	// AttributionOff - never annotate.
	AttributionOff AttributionMode = "off"
	// AttributionOn - always annotate against the configured identity.
	AttributionOn AttributionMode = "on"
	// AttributionAuto - annotate only if the viewer's email resolves to a
	// known git author in recent history; the noise disappears for people it
	// means nothing to.
	AttributionAuto AttributionMode = "auto"
)

type CommitInfo

type CommitInfo struct {
	SHA         string    `json:"sha"`
	Subject     string    `json:"subject,omitempty"`
	Author      string    `json:"author,omitempty"`
	AuthorEmail string    `json:"-"`
	At          time.Time `json:"at,omitzero"`
	URL         string    `json:"url,omitempty"`
	Request     string    `json:"request,omitempty"`    // e.g. "!1234"
	RequestURL  string    `json:"requestUrl,omitempty"` // MR / PR link
	TaskID      string    `json:"taskId,omitempty"`     // e.g. "PROJ-123"
	TaskURL     string    `json:"taskUrl,omitempty"`
	Mine        bool      `json:"mine,omitempty"`
}

CommitInfo is a commit as the report presents it. Author emails are kept out of the JSON on purpose - the report is often shown beyond the dev team.

type Component

type Component struct {
	Name string
	Live LiveProvider // nil -> Assumed
}

Component is a named deployable unit (backend, web, worker...) with its own live source.

type ComponentReport

type ComponentReport struct {
	Name  string      `json:"name"`
	Live  *LiveReport `json:"live"`
	Error string      `json:"error,omitempty"`
}

ComponentReport is one component's Live answer. Live is nil only when nothing could be established at all (no provider and no Green to assume).

type Drift

type Drift struct {
	// Leader is the most-ahead component; the others are measured against it.
	Leader  string `json:"leader"`
	Message string `json:"message"` // e.g. "web 1 behind backend"
}

Drift flags components that report different Live commits when they should move together (your backend shipped, your web didn't).

type Forge

type Forge interface {
	// Head returns the latest commit on the tracked branch (the HEAD tier).
	Head(ctx context.Context, branch string) (Ref, error)
	// LatestGreen returns the newest commit on branch whose CI pipeline
	// passed (the Green tier).
	LatestGreen(ctx context.Context, branch string) (Ref, error)
	// Resolve returns full commit metadata for a SHA, short SHA or tag.
	Resolve(ctx context.Context, sha string) (Ref, error)
	// Behind counts how many commits `to` has that `from` does not.
	Behind(ctx context.Context, from, to string) (int, error)
	// Recent returns up to limit latest commits on branch. Used by the
	// attribution auto-gate to build the recent-history author set.
	Recent(ctx context.Context, branch string, limit int) ([]Ref, error)
	// CommitURL returns a browsable URL for a commit.
	CommitURL(sha string) string
	// RequestURL returns a browsable URL for a merge/pull request id.
	RequestURL(id string) string
}

Forge is the umbrella seam for a git host (GitLab, GitHub, Gitea...). It answers the abstract questions every host can answer; concrete implementations are swappable, so GitLab-first does not mean GitLab-only.

type ForgeInfo

type ForgeInfo struct {
	Kind   string `json:"kind"`
	Host   string `json:"host,omitempty"`
	Repo   string `json:"repo"`
	Branch string `json:"branch"`
}

ForgeInfo describes the forge for the report header; it carries no behavior.

type GreenInfo

type GreenInfo struct {
	CommitInfo
	Pipeline   string `json:"pipeline,omitempty"`
	BehindHead int    `json:"behindHead,omitempty"`
}

GreenInfo is the Green tier: the latest commit with a passing pipeline.

type Identity

type Identity interface {
	// ViewerEmails returns the viewer's known emails; may be empty.
	ViewerEmails(ctx context.Context) ([]string, error)
}

Identity answers who is viewing the report, for "yours" attribution. The CLI reads git config user.email; a host application hands in the logged-in user's email.

type LiveConfidence

type LiveConfidence string

LiveConfidence states how much we actually know about the Live tier. It is a first-class field, not a boolean, so the renderer can be honest. Ranked highest first: Probed, Reported, Recorded, Assumed.

const (
	// Probed - the running artifact self-reported its commit (highest
	// fidelity).
	Probed LiveConfidence = "probed"
	// Reported - a user-supplied command asserted the running commit; truth
	// we did not observe ourselves.
	Reported LiveConfidence = "reported"
	// Recorded - the forge's deployment record for an environment: the commit
	// CI deployed, not what the host runs now.
	Recorded LiveConfidence = "recorded"
	// Assumed - no live source at all; Green stands in, clearly labeled.
	Assumed LiveConfidence = "assumed"
)

func (LiveConfidence) Weaker

func (c LiveConfidence) Weaker(other LiveConfidence) bool

Weaker reports whether c is a weaker claim than other. An unknown confidence ranks weakest, so it never passes for a stronger one.

type LiveInfo

type LiveInfo struct {
	// SHA is a full or short commit SHA, or anything the Forge can resolve
	// to one (a tag, an image-ref suffix).
	SHA     string
	BuiltAt time.Time // zero when the provider cannot know
	// State is the container state as the provider reported it, verbatim.
	// Empty (unknown), "running" and "healthy" mean serving; see Serving.
	State      string
	Confidence LiveConfidence
	// Rollout is a deploy newer than SHA that has not succeeded; nil when
	// there is none or the provider cannot see deploys.
	Rollout *Rollout
}

LiveInfo is what a LiveProvider can know on its own: a commit-ish and, sometimes, when it was built, the container's state and a newer deploy that has not succeeded. The engine resolves the rest through the Forge.

type LiveProvider

type LiveProvider interface {
	Live(ctx context.Context) (LiveInfo, error)
}

LiveProvider answers what is actually running for one component. A nil provider means the Assumed fallback: Live is taken to be Green, labeled as an assumption - the engine implements that itself because only it knows Green.

type LiveReport

type LiveReport struct {
	CommitInfo
	Confidence LiveConfidence `json:"confidence"`
	BuiltAt    time.Time      `json:"builtAt,omitzero"`
	// State is the provider-reported container state, absent when unknown or
	// when Live is assumed from Green.
	State       string `json:"state,omitempty"`
	BehindGreen int    `json:"behindGreen,omitempty"`
	BehindHead  int    `json:"behindHead,omitempty"`
	// Rollout is a newer deploy that is pending or failed.
	Rollout *RolloutReport `json:"rollout,omitempty"`
}

LiveReport is the Live tier for one component, with its confidence and how far it lags the other tiers. Keep the numbers separate: Live is N behind Green is M behind HEAD - never collapse them.

func (*LiveReport) Serving

func (l *LiveReport) Serving() bool

Serving reports whether this Live is serving traffic: true unless the provider reported a state other than running or healthy.

type Params

type Params struct {
	Project     string
	Environment string
	Forge       Forge
	ForgeInfo   ForgeInfo
	// Branch is the tracked branch, default "main"; Collect copies it into
	// the report's Forge.Branch.
	Branch      string
	Components  []Component
	Identity    Identity        // nil -> no attribution
	Attribution AttributionMode // default AttributionAuto
	// Identities is the alias map: one person, many emails (work vs
	// personal, forge noreply). Any match pulls in the whole group.
	Identities map[string][]string
	Task       *TaskConfig
	// RecentLimit is how deep the attribution auto-gate looks for authors;
	// default 50.
	RecentLimit int
}

Params configures a single Collect run: one project, one environment.

type Ref

type Ref struct {
	SHA         string
	Subject     string
	AuthorName  string
	AuthorEmail string
	At          time.Time
	URL         string
}

Ref is a resolved commit reference on the tracked branch.

func (Ref) IsZero

func (r Ref) IsZero() bool

IsZero reports whether the ref carries no commit at all.

type Report

type Report struct {
	Project     string `json:"project"`
	Environment string `json:"environment"`
	// Forge.Branch is always the branch Collect tracked.
	Forge       ForgeInfo         `json:"forge"`
	Head        *CommitInfo       `json:"head,omitempty"`
	Green       *GreenInfo        `json:"green,omitempty"`
	Components  []ComponentReport `json:"components"`
	Drift       *Drift            `json:"drift"`
	Attribution AttributionMode   `json:"attribution"`
	// Errors carries degradation notes (a tier that could not be fetched, an
	// identity lookup that failed). A failed provider is on its component's
	// Error instead. Presence of errors never prevents a report: degrade
	// gracefully, render something useful.
	Errors []string `json:"errors,omitempty"`
}

Report is the core's whole output and a public API: its JSON shape only changes additively. Rendering it is the host's job - the CLI's tty renderer and an admin popover are just two consumers.

func Collect

func Collect(ctx context.Context, p Params) (*Report, error)

Collect asks the seams their questions and applies the rules: tier comparison, assumed-fallback, drift, attribution. It fails only on unusable Params; anything the world refuses to answer becomes a labeled degradation inside the Report instead.

type Rollout

type Rollout struct {
	SHA       string
	Status    RolloutStatus
	StartedAt time.Time // zero when unknown
}

Rollout is a deploy of SHA that is in flight or failed.

type RolloutReport

type RolloutReport struct {
	CommitInfo
	Status    RolloutStatus `json:"status"`
	StartedAt time.Time     `json:"startedAt,omitzero"`
}

RolloutReport is a deploy newer than Live that has not succeeded.

type RolloutStatus

type RolloutStatus string

RolloutStatus is the state of a deploy that is not (yet) live.

const (
	// RolloutPending - the deploy is running.
	RolloutPending RolloutStatus = "pending"
	// RolloutFailed - the deploy failed, so the older Live commit kept running.
	RolloutFailed RolloutStatus = "failed"
)

type TaskConfig

type TaskConfig struct {
	// Pattern is a regexp matched against the commit subject; the whole
	// match is the task id (e.g. `PROJ-\d+`).
	Pattern string
	// URL is the link template; "{id}" is replaced with the matched id.
	URL string
}

TaskConfig links task-tracker ids found in commit subjects (Jira, Linear, ...) to their URLs. Ported as-is from Ruby onair's task: config.

Directories

Path Synopsis
cmd
onair command
Command onair answers "which commit is actually running" for the project described by .onair.yml.
Command onair answers "which commit is actually running" for the project described by .onair.yml.
Package config loads and validates .onair.yml.
Package config loads and validates .onair.yml.
Package gitlab implements the onair.Forge seam against the GitLab REST API.
Package gitlab implements the onair.Forge seam against the GitLab REST API.
Package live provides the host-side LiveProvider implementations: probe (the /-/version convention), command (the universal adapter - any CLI's output is the answer) and static (a ref handed in directly, e.g.
Package live provides the host-side LiveProvider implementations: probe (the /-/version convention), command (the universal adapter - any CLI's output is the answer) and static (a ref handed in directly, e.g.
Package render turns a Report into output.
Package render turns a Report into output.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL