Architecture
About 1965 words
This page explains how unifi-cli is put together and where a change belongs. It's for contributors, and for anyone who wants to know why the tool behaves the way it does. The step-by-step instructions for common changes are in CONTRIBUTING.md.
Bricks, manual, model
The repository is organized like a box of Lego.
pkg/ holds the bricks: every reusable building block, one package per domain. Most of the code lives here on purpose, including code that many Go projects would hide in internal/, because a brick someone else can import is a brick someone else can build on.
internal/ is the instruction manual. It has one package, internal/app, which wires bricks together: it builds the credential chain, the API clients with their tracing decorators, the logger and the theme catalog. It defines no bricks of its own.
cmd/ builds the model. cmd/unifi/commands exposes the wiring as cobra commands, cmd/unifi/internal holds helpers that only commands need, and cmd/unifi/testing holds the golden tests of whole commands. cmd/unifi-mock is the demo controller's binary.
api/ holds the definitions everything else speaks: the types for clients, devices, events and statistics, the manifest envelope, and the generated JSON schemas.
Dependencies point one way, from cmd down to api. A linter rule (depguard) fails the build when a package under pkg/ or api/ imports internal/ or cmd/.
The packages
| Package | What it is |
|---|---|
pkg/client/unifi | The client for a UniFi Network controller |
pkg/client/sitemanager | The client for the Site Manager API and its cloud connector |
pkg/client/sso | The experimental UI account sign-in |
pkg/client/transport | Shared HTTP: TLS, retries, error mapping |
pkg/config | The configuration file and contexts |
pkg/credential | Secret stores: environment, keychain, file, and the chain over them |
pkg/secret | The one classifier that decides which field names are secrets |
pkg/cache | The on-disk cache, with a guard that refuses to store secrets |
pkg/resource | The registry of configuration kinds |
pkg/manifest | Export, plan, diff, apply and the redaction of manifests |
pkg/filter | The filter language |
pkg/query | Sorting, filtering and name resolution for clients, devices, ports and events |
pkg/dashboard | Loading and caching the data behind the dashboard |
pkg/topology | Building the device tree |
pkg/shell | The engine of unifi shell: grammar, modes, completion, scripts |
pkg/prompt | The prompt segment and its snippets |
pkg/output | JSON and YAML encoding |
pkg/logging | The rotating, redacting log |
pkg/tui | Theme, components and views |
pkg/mockcontroller | The demo controller |
Interfaces live with what they abstract
A domain with a seam declares its interface next to the thing it abstracts, and its implementations are sibling packages:
pkg/client/unifi/
interface.go the Client interface and the types it speaks
unifi/ the real client, over HTTP
unifiotel/ the same interface, wrapped with OpenTelemetry spans
mocks/ a hand-written mock for testsEach implementation carries a compile-time assertion that it satisfies the interface, so adding a method to interface.go produces a list of everything that needs to follow. The tracing decorator wraps any implementation of the interface, which is how internal/app stacks real client, then spans, without either knowing about the other.
pkg/config, pkg/credential, pkg/cache, pkg/client/sitemanager and pkg/dashboard follow the same layout.
One client, two API families
pkg/client/unifi is the only thing that talks to a controller. Its interface is phrased in terms of what unifi-cli does (list devices, set a port, list the objects of a kind), not in terms of endpoints.
The implementation uses the official Network Integration API wherever it covers an operation, and the controller's internal API for the rest. Which one serves a request is a detail of the client; commands don't know. When the official API gains an endpoint, the client can move to it without a change above. API coverage lists the current split.
The client always talks to "the Network application at this base URL". Whether that URL is a console on the LAN or the cloud connector is decided one layer up, in internal/app, from the context's account type.
Kinds are data
The configuration subjects (networks, wifi, firewall policies and the rest) aren't 22 hand-written command sets.
pkg/resource holds a registry of descriptors. A descriptor is pure data about a kind: its name and plural, which API family and path serve it, which fields carry the ID and the name, which fields tell same-named objects apart, and which columns its table shows.
Three consumers read the registry:
- the client, to list, create, update and delete objects of any kind through one set of methods;
- the manifest engine, to export, plan and apply;
cmd/unifi/internal/resourcecmd, which builds the shared verbs (get,describe,create,set,edit,enable,disable,delete) for a kind from its descriptor.
A subject package such as cmd/unifi/commands/commands/networks is therefore small: it names the kind, adds the typed flags (--vlan, --subnet) and the help text, and lets resourcecmd do the rest.
Specs pass through as the controller's own JSON. unifi-cli doesn't model every field of every kind, which is why a field Ubiquiti adds tomorrow shows up in describe and works with --set without a release. The price is that validation of field values is the controller's job.
The terminal UI in three layers
pkg/tui/theme design tokens: colors, border, glyphs
pkg/tui/component/<name> one pure Render per component
pkg/tui/views/<screen> components assembled into a screenThe theme resolves a theme file and a color scheme into a theme.Theme value.
A component is a package with a constructor, functional options and a Render(width) that returns a string. The library has tables, key-value lists, panels, gauges, bar charts, sparklines, braille graphs, heatmaps, the port grid, trees, the box diagram of the topology, notices, tab bars, headers and footers. Render is pure: no I/O, no clock, no terminal queries. Everything it needs arrives through the constructor.
A view assembles components into what a command prints: the clients table, the device detail, the dashboard. Commands call views and never style anything themselves.
Goldens
Because rendering is pure, it's testable byte for byte. Every component and view has golden files under testdata/, in two flavors: .ascii with the plain text, which is readable in a code review, and .ansi with the escape sequences, which pins the colors. Whole commands have goldens too, under cmd/unifi/testing/testdata, recorded against the mock client.
A golden is a claim that this output is correct. mise run test:update re-records them, and the diff of the recorded files is what a reviewer reads.
The interactive programs (the dashboard, the shell) are bubbletea models in their view packages. Their View is built from the same pure renders, so a frame of the full-screen dashboard and the output of unifi dashboard --once come from the same code.
The dashboard
pkg/dashboard loads a snapshot: statistics, devices, clients and events in a few concurrent requests, with history kept between refreshes. A widget (pkg/tui/views/dashboard/components, one file per type) is a stateless value that draws its body from a snapshot and its options. The dashboard view reads the rows from the configuration, asks each widget for its preferred height, distributes the width by span, and frames each body in a panel.
Because widgets are stateless and the snapshot is plain data, --output json on the dashboard is the snapshot itself.
The same property makes the live view fast to open. The last snapshot is kept in the cache, so the dashboard draws it at once, marked as cached, and replaces it part by part as the requests of the first refresh come back. A refresh pauses while the terminal isn't focused and backs off when the controller rate-limits.
Caching and shared requests
pkg/cache is a small on-disk store under the state directory for answers that are slow to fetch and rarely change: a controller's site list and version, completion candidates, the last dashboard and topology snapshot, and the terminal's background color. Each entry has a lifetime of minutes to a day, and --no-cache bypasses the store. A guard built on pkg/secret refuses any value with a field named like a secret, so a mistake fails in a test instead of writing a key to a file.
Within one command, requests are shared: two parts of a view that need the device list cause one request.
The shell
pkg/shell is an engine without a terminal: it takes a line and returns blocks of output. Its grammar is a tree of keyword and argument nodes per mode, and the same tree drives parsing, abbreviations, ? help and tab completion, so the three can't disagree. The engine talks to the controller through a small Backend interface, implemented over the regular client in pkg/shell/backend.
The interactive front end in pkg/tui/views/shell and the script runner behind unifi shell -c are two callers of that engine.
One definition of "secret"
pkg/secret decides from a field's name whether it holds a secret. The log redacts by it, the cache refuses to store by it, and manifests, describe and the shell redact by it, so the three can't disagree about what is sensitive. The rules are in the package's doc comment: UniFi's x_ prefix, a list of secret words, a trailing key, and exceptions for names that describe a secret instead of holding one, such as x_ssh_auth_password_enabled or keyExpiresAt.
Errors
Every function that can fail returns a humane.Error: a problem sentence plus advice on what to do about it. Each layer wraps the error from below with its own problem and advice, which produces the "Caused by" chain you see when a command fails. main renders the error once, logs it, and maps it to an exit code.
The rule that an error without advice doesn't get merged is why the tool's failures read the way they do.
Extending unifi-cli
Add a configuration kind
- Add a descriptor to
pkg/resource/registry.go. - Serve the kind from
pkg/mockcontroller, with fixture data. - Add a subject package under
cmd/unifi/commands/commands/with the typed flags, and wire it incommands/root.go. - Record goldens, then run
mise run schemaandmise run docs:reference.
export, diff, apply, resources get, shell completion and unifi shell's resource <kind> mode pick the kind up from the registry.
Add a widget
- Add a file to
pkg/tui/views/dashboard/componentswith a type that implements thewidget.Widgetinterface frompkg/tui/views/dashboard/widget. Besides drawing itself, a widget declares which parts of the snapshot it reads (Sources), so the dashboard only fetches what the configured layout needs. - Add it to
All()incomponents.go. - Add a golden.
--list-widgets, --widget and the dashboard's handling of unknown types all read from All(). If the widget needs data the snapshot doesn't have, that's a change to pkg/dashboard and the client first.
Add a component
Create pkg/tui/component/<name> with the component, its options and a table-driven golden test; pkg/tui/component/table is the one to copy from. Keep Render pure, or the goldens will flicker.
Add a theme
Drop a YAML file into pkg/tui/theme/builtin/. The catalog embeds the directory, and the theme tests cover every built-in theme, including a contrast check.
Protect and Access
unifi-cli covers UniFi Network today. The layout leaves room for the other applications without restructuring: a client for Protect would be pkg/client/protect with the same interface-package layout, its subjects would be siblings under cmd/unifi/commands/commands/, and its kinds would get an API group of their own next to network.unifi.specht-labs.de. The connection handling already separates "which console" from "which application on it".
None of that exists yet. It's a description of where it would go.
