ui

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: GPL-3.0, LGPL-3.0 Imports: 55 Imported by: 0 modules, 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.

Documentation

Overview

Package ui implements sind ui, a local web UI for sind.

It serves server-rendered pages (html/template) with htmx and one Server-Sent Events stream per tab for live updates, all embedded in the binary. It listens on 127.0.0.1 only, and lets in only the user's own processes holding the per-run token from the URL it prints.

Extending sind ui

A part of sind ui, such as the Clusters page or the task dock, adds itself to the server from files of its own, without editing server.go, sse.go or the layout. Parts built side by side then touch no common file. A part needs up to five things:

  1. Templates, in web/templates/NAME.tmpl. The server parses every file there into one set, so a block name is global: prefix yours with the part's name. A page defines the block "page-NAME" for its content; a fragment defines a block of its own name. Both are executed with a *View.
  2. A page, registered from an init function with RegisterPage: a Page has a route ("GET /clusters/{name}"), a title, the key of the rail entry to light, the fragments it keeps live, and a Load function that fills View.Data from View.Snap (the snapshot) and View.Params (the route's wildcards and the declared query keys). Load may return ErrNotFound (404), or a *Miss, which says what is missing and offers the closest matches on the Not found page, or an error that wraps ErrBadRequest (400), and only reads.
  3. Fragments, registered with RegisterFragment. A fragment is a block of HTML that live updates morph into its element. Its page places it with <div hx-swap="morph:innerHTML" sse-swap="NAME">{{fragment "NAME" .}}</div>, so that the elements that stay keep their animations, focus and open state (idiomorph's htmx extension): the template function fragment runs the fragment's Load on a copy of the view and executes its block, so the page holds what /events would send. /events renders the fragment again when a topic it depends on changes (Topics for exact topics, Prefixes for prefixes such as "run/", Watch for topics that depend on the Params), and sends it only when its HTML differs from what that stream sent before. A Shell fragment is part of every page; the rail and the task dock are two.
  4. Routes for everything else, registered with RegisterRoute: dialogs, POST actions, helpers that answer with one fragment. A route is a function of the *Server and the request. A request that changes something has passed the Origin and CSRF checks and has its form parsed (at most 64 KiB) when the route runs; use Server.View for its Params, Server.Write and Server.Fragment to answer, Server.Fail for an error, and the template block "csrf-field" in a form that a browser sends without script.
  5. Background work, registered with RegisterService: collectors that write the store, runners. A Service has a Setup, which runs before the server is built and hands what routes need to the other parts through Env.Put, and a Run, which runs until the context ends. Every external command goes through Env.Exec.

A service can also learn what the open pages need. Env.AddWatcher, called from Setup, adds a Watcher: each /events stream calls it with the exact topics its fragments depend on (Fragment.Topics and what Fragment.Watch returns for the stream's Params) when it opens, and calls the function it returns when it ends. The collectors count the status topics this way and read the status of a cluster only while a page shows it. The collect service also puts two plain funcs in Env for other parts: ColRefreshKey (func(realm string), read that realm again now) and ColDoctorKey (func(), run the host checks again). A part that finds neither (nil) works without them.

Styles and scripts need no registration: web/static/css/*.css and web/static/js/*.js are linked from the layout, in name order, after app.css and app.js, with content-hashed URLs. No inline script or style works: the Content-Security-Policy allows files of this origin only. Template functions come from AddFuncs and the counts behind the rail entries from SetNavCount; name them with the part's prefix, as the names are global.

Everything registered lives in a Registry. The init functions fill the default one, which Run uses; tests build their own with NewRegistry.

Index

Constants

View Source
const (
	// ColRefreshKey holds a func(realm string) that reads that realm again
	// now, such as after a task that changed it ended.
	ColRefreshKey = "collect.refresh"
	// ColDoctorKey holds a func() that runs the host checks again.
	ColDoctorKey = "collect.doctor"
	// ColMonitoringIntervalKey holds the interval at which the monitoring
	// stacks are read, a value with the methods Get() time.Duration and
	// Set(time.Duration).
	ColMonitoringIntervalKey = "collect.monitoring-interval"
)

The Env keys that the collectors provide, for the parts that act on them. The values are plain funcs and interfaces, so that no part imports another.

Variables

View Source
var ErrBadRequest = errors.New("bad request")

ErrBadRequest is what a Load returns for a parameter that does not pass its check. Wrap it with fmt.Errorf("...: %w", ErrBadRequest); the server answers 400 and says what the error says.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is what a Load returns for an item that does not exist: the server answers 404 with the "Not found" page.

Functions

func AddFuncs

func AddFuncs(m template.FuncMap)

AddFuncs adds template functions to the default registry.

func RegisterFragment

func RegisterFragment(f Fragment)

RegisterFragment adds a fragment to the default registry.

func RegisterPage

func RegisterPage(p Page)

RegisterPage adds a page to the default registry; it panics when the page is wrong, as the init function that calls it is a program error.

func RegisterRoute

func RegisterRoute(rt Route)

RegisterRoute adds a route to the default registry.

func RegisterService

func RegisterService(s Service)

RegisterService adds a service to the default registry.

func Run

func Run(ctx context.Context, o Options) error

Run serves sind ui until ctx ends. When another sind ui of the user runs, it opens that one's URL and returns.

func SetNavCount

func SetNavCount(key string, fn func(store.Snapshot) NavCount)

SetNavCount sets the count of the rail entry key in the default registry.

func SetNavCountAt

func SetNavCountAt(key string, fn NavCountFunc)

SetNavCountAt sets the count of the rail entry key in the default registry, from a function that needs the time too.

Types

type Env

type Env struct {
	Store *store.Store
	// Exec runs external commands, and is the one that tests replace.
	Exec cmdexec.Executor
	Log  *slog.Logger
	// Opts are the options Run was called with, defaults filled in.
	Opts Options
	// Addr is host:port that the server listens on.
	Addr string
	// contains filtered or unexported fields
}

Env is what services and routes share: the store, the executor through which every external command runs, and the options.

func (*Env) AddWatcher

func (e *Env) AddWatcher(w Watcher)

AddWatcher adds a Watcher. Call it from Service.Setup, which runs before the server is built.

func (*Env) Get

func (e *Env) Get(key any) any

Get returns what Put kept under key, or nil.

func (*Env) Put

func (e *Env) Put(key, value any)

Put keeps value under key, for a route or another service to Get. The key is a value of a type of the caller's own, as with context values.

type Fragment

type Fragment struct {
	// Name is the SSE event and the name of the template block.
	Name string
	// Topics are the topics the fragment depends on: it is rendered again
	// when one of them changes.
	Topics []store.Topic
	// Prefixes are topic prefixes it depends on, such as "run/" for every
	// store.RunTopic. The prefix "" is every topic.
	Prefixes []string
	// Watch returns the topics that depend on the request's Params, such
	// as the one run of the run page. It may be nil.
	Watch func(p Params) []store.Topic
	// Params are the query keys the fragment reads; /events passes on no
	// others.
	Params []string
	// Shell makes every page include the fragment.
	Shell bool
	// Load fills v.Data from v.Snap and v.Params. It may be nil.
	Load func(v *View) error
}

A Fragment is a block of HTML that live updates replace.

type LogsTabView

type LogsTabView struct {
	Realm, Cluster string
	// Nodes are the nodes of the cluster, the one shown selected.
	Nodes []logsNodeOption
	Node  string
	// Source is docker or journal.
	Source string
	// Units are the units of the node shown, after the entry for all.
	Units []logsChoice
	Unit  string
	// Lines are the line counts to start with.
	Lines []logsChoice
	// Count is the line count that the stream starts with.
	Count int
	// Query is the filter, and Errors keeps errors and warnings only.
	// QueryMax is the longest filter, the longest value of a parameter.
	Query    string
	QueryMax int
	Errors   bool
	// Sind is the command that the terminal line starts with, and Suffix
	// what follows a short name in a node argument.
	Sind, Suffix string
	// Keep is how many lines the tab keeps.
	Keep int
}

LogsTabView is what the Logs tab of the cluster page shows.

func (*LogsTabView) Command

func (d *LogsTabView) Command() string

Command returns the command of the terminal that shows the same log.

func (*LogsTabView) KeepText

func (d *LogsTabView) KeepText() string

KeepText is Keep for a sentence: 10,000.

type Miss

type Miss struct {
	// What says what is missing, in one sentence.
	What string
	// Hint is a second sentence, or empty.
	Hint string
	// Links are the ways forward, the closest match first.
	Links []MissLink
}

Miss is an ErrNotFound that says what is missing and where to go instead. The Not found page shows it: a Load or a route returns it in place of a plain ErrNotFound when it knows better than "nothing here". errors.Is(m, ErrNotFound) holds.

func (*Miss) Error

func (m *Miss) Error() string

Error returns What.

func (*Miss) Is

func (m *Miss) Is(target error) bool

Is makes a Miss an ErrNotFound.

type MissLink struct {
	Label string
	URL   string
	// Note follows the link as plain text, such as "in realm ci".
	Note string
}

MissLink is a way forward of a Miss.

type NavCount struct {
	// Text is the count with its unit; empty shows none, or a dot with
	// Class ok.
	Text string
	// Class colours it: "", "run", "warn", "bad", or "ok" for the dot.
	Class string
	// Label says what the badge means in words, for screen readers and
	// as its tooltip, such as "1 node needs a look".
	Label string
}

NavCount is the badge behind a rail entry: a count with its unit, such as "1 down", or a dot when all is well.

type NavCountFunc func(sn store.Snapshot, now time.Time) NavCount

NavCountFunc returns the badge of a rail entry from the snapshot, at the time of the view.

type NavItem struct {
	// Key is what Page.Nav names, and the ID of the entry's icon in
	// web/static/icons.svg.
	Key   string
	Label string
	Href  string
	// Group is the label of the list it stands in.
	Group string
	// Main puts the entry in the bar at the bottom of a phone's screen;
	// the others are in the bar's More sheet.
	Main bool
}

NavItem is an entry of the rail.

type Options

type Options struct {
	// Port to listen on; 0 picks a free one.
	Port int
	// NoOpen keeps the browser closed; the URL is printed either way.
	NoOpen bool
	// RuntimeDir is $XDG_RUNTIME_DIR, where the running UI is recorded so
	// that a second sind ui opens it instead of starting another. Empty
	// records nothing.
	RuntimeDir string
	// Exec runs the external commands; nil is the real one.
	Exec cmdexec.Executor
	// GOOS names the operating system, as runtime.GOOS does; empty is
	// runtime.GOOS.
	GOOS string
	// Getenv reads the variables that tell whether a browser can open
	// (SSH_CONNECTION, DISPLAY, WAYLAND_DISPLAY), as os.Getenv does; nil
	// reads every variable as unset, so that on Linux no browser opens.
	Getenv func(string) string
	// Stderr gets the URL and the log; nil discards both.
	Stderr io.Writer
	// Demo serves made-up clusters and plays the commands of the dialogs:
	// no Docker, no child process, nothing written. It does not record
	// itself in RuntimeDir, so that it never stands in for a real sind ui.
	Demo bool
	// Still makes the demo stand at demo.Epoch and play nothing, so that its
	// pages are the same on every run. It is for screenshots and needs Demo.
	Still bool
	// MonitoringInterval is how often the monitoring stacks are read
	// while a page is open, between collect.MinInterval and
	// collect.MaxInterval; 0 is collect.MonitoringEvery. The Monitoring
	// page changes it.
	MonitoringInterval time.Duration
	// contains filtered or unexported fields
}

Options configure Run.

type Page

type Page struct {
	// Name identifies the page and names its content block
	// "page-NAME". It is lower case, letters, digits and hyphens.
	Name string
	// Pattern is the route as http.ServeMux reads it, with the method:
	// "GET /clusters/{name}". Its wildcards become Params.
	Pattern string
	// Title is the page title. Load may change it.
	Title string
	// Nav is the key of the rail entry to light, one of the NavItem keys;
	// empty lights none.
	Nav string
	// Params are the query keys that the page reads, besides the
	// wildcards of its Pattern.
	Params []string
	// Fragments are the fragments of the page that live updates replace.
	// The shell fragments (the rail, the task dock) are always included.
	Fragments []string
	// Load fills v.Data, and may set v.Title. It may return ErrNotFound or
	// ErrBadRequest. It runs on each request, so it only reads.
	Load func(v *View) error
}

A Page is a screen of sind ui at its own address.

type Params

type Params = url.Values

Params are the values a page or a fragment reads from its request: the wildcards of the route (as in {name}) and the query. The server keeps only the keys that the page or the fragment declares, and no value longer than maxParamLen. A Load checks each value again: the browser sends whatever it likes.

type PgRealmOption

type PgRealmOption struct {
	Value    string
	Label    string
	Selected bool
}

PgRealmOption is an entry of the realm picker.

type PgRealmScope

type PgRealmScope struct {
	Realm   string
	ShowAll string
}

PgRealmScope is what a page that shows one realm says about it: the realm, and the address of the same page with every realm.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds what parts of sind ui register.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry.

func (*Registry) AddFragment

func (r *Registry) AddFragment(f Fragment)

AddFragment adds a fragment. It panics for a name that is invalid or already taken.

func (*Registry) AddFuncs

func (r *Registry) AddFuncs(m template.FuncMap)

AddFuncs adds template functions. It panics for a name that is taken.

func (*Registry) AddPage

func (r *Registry) AddPage(p Page)

AddPage adds a page. It panics for a name or a pattern that is invalid or already taken.

func (*Registry) AddRoute

func (r *Registry) AddRoute(rt Route)

AddRoute adds a route.

func (*Registry) AddService

func (r *Registry) AddService(s Service)

AddService adds a service. It panics for a name that is taken.

func (*Registry) SetNavCount

func (r *Registry) SetNavCount(key string, fn func(store.Snapshot) NavCount)

SetNavCount sets the count behind the rail entry key.

func (*Registry) SetNavCountAt

func (r *Registry) SetNavCountAt(key string, fn NavCountFunc)

SetNavCountAt sets the count behind the rail entry key, from a function that needs the time too.

type Route

type Route struct {
	// Pattern is the route as http.ServeMux reads it, with the method:
	// "POST /clusters/{name}/delete".
	Pattern string
	// Handle answers the request. Use s.View, s.Write and s.Fail.
	Handle func(s *Server, w http.ResponseWriter, r *http.Request)
	// FetchOnly lets in only the requests that a page of this server sent
	// itself, as its live parts do, and no navigation from another page. Set
	// it on a route that starts work.
	FetchOnly bool
}

A Route is a handler for the paths that no page serves.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server serves sind ui's pages and live updates for one store.

func (*Server) Env

func (s *Server) Env() *Env

Env returns what the server shares with the services.

func (*Server) Fail

func (s *Server) Fail(w http.ResponseWriter, r *http.Request, err error)

Fail answers a request whose Load or route failed: ErrNotFound with the Not found page and what a Miss in err says; ErrBadRequest with 400 and its message, in the layout when a browser navigated to the address; anything else with 500 and a line in the log.

func (*Server) Fragment

func (s *Server) Fragment(w http.ResponseWriter, r *http.Request, name string)

Fragment answers a request with the fragment name: its Load runs on the request's Params (the fragment's own keys) and its block is the response.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the server's handler with every check in front of it. The static files need no session: they hold no data, and the page that asks a browser to sign in uses them.

func (*Server) Store

func (s *Server) Store() *store.Store

Store returns the store that the pages read.

func (*Server) View

func (s *Server) View(r *http.Request, keys ...string) (*View, error)

View returns the view of a request: the current snapshot, the session's CSRF token, and as Params the wildcards of the route that matched and the values of the named keys, from the query and from the form. A value that is too long is an ErrBadRequest.

func (*Server) Write

func (s *Server) Write(w http.ResponseWriter, r *http.Request, status int, name string, v *View)

Write renders the block name with v and writes it as the response with status. A render that fails goes to Fail: a fragment of the page that returns ErrNotFound makes the page a 404, and anything else a 500.

type Service

type Service struct {
	// Name orders the services: Setup and start go by name.
	Name string
	// Setup runs once before the server is built, to make what routes
	// need and to put it in env (Env.Put). It may be nil.
	Setup func(env *Env) error
	// Run runs in its own goroutine until ctx ends, and may be nil.
	Run func(ctx context.Context, env *Env)
}

A Service is background work of sind ui.

type View

type View struct {
	// Page is the name of the page, the empty string in a fragment that
	// /events renders and on the Not found page.
	Page string
	// Title is the page's title, set by Page.Title and changed by Load.
	Title string
	// Nav is the key of the rail entry that is lit. It is the page's Nav,
	// and /events passes it on to the rail fragment.
	Nav string
	// Snap is the snapshot at the start of the render. Load reads it and
	// never changes it.
	Snap store.Snapshot
	// Now is the time to measure from.
	Now time.Time
	// Params are the values of the request that Load reads.
	Params Params
	// Data is what Load sets, for the template.
	Data any
	// CSRF is the session's token, for forms: {{template "csrf-field" .}}.
	CSRF string
	// Addr is host:port that sind ui listens on.
	Addr string
	// Events is the URL of the page's live updates, empty for none.
	Events string
	// Content is the name of the block that holds the page's content.
	Content string
	// Asset returns the URL of a static file by its path below
	// web/static, such as "app.css".
	Asset func(string) string
	// Vendor returns the URL of a script of go-clikit's localweb/htmx by
	// its name, such as htmx.Script.
	Vendor func(string) string
	// HTMXConfig is the configuration of htmx that the layout puts in the
	// page, htmx.Config.
	HTMXConfig string
	// Styles and Scripts are the URLs of the extra files that every page
	// links: web/static/css/*.css and web/static/js/*.js.
	Styles  []string
	Scripts []string
	// contains filtered or unexported fields
}

View is what a template renders from.

func (*View) LogsTab

func (v *View) LogsTab() *LogsTabView

LogsTab returns what the Logs tab of the view's cluster shows, from the view's Params. A value that does not fit, such as a node that the cluster does not have, falls back to the default.

func (*View) PgRealmNext

func (v *View) PgRealmNext() string

PgRealmNext returns the address that the realm picker goes to.

func (*View) PgRealmOptions

func (v *View) PgRealmOptions() []PgRealmOption

PgRealmOptions returns the entries of the realm picker in the top bar.

func (*View) PgRealmScope

func (v *View) PgRealmScope() PgRealmScope

PgRealmScope returns the realm that the page shows, and the address of the page with every realm.

type Watcher

type Watcher func(topics []store.Topic) (release func())

A Watcher is told which topics a live stream (/events) watches: when the stream opens it is called with the topics of the stream's fragments, and the function it returns is called when the stream ends. A collector uses it to read more often what an open page shows, such as the status of a cluster whose page is open. The topics are the exact ones of the fragments (Fragment.Topics) and those their Watch functions return for the stream's Params; a fragment that depends on a prefix names none. The function may be called concurrently and must not block.

Directories

Path Synopsis
Package action turns the forms of sind ui's dialogs into the sind commands they run.
Package action turns the forms of sind ui's dialogs into the sind commands they run.
Package activity follows sind's event log, the go-clikit event log (v1) that every sind command appends to and that sind ui reads its progress display from, and reduces its lines to store.Run values: each run is one command with the tree of its spans.
Package activity follows sind's event log, the go-clikit event log (v1) that every sind command appends to and that sind ui reads its progress display from, and reduces its lines to store.Run values: each run is one command with the tree of its spans.
Package collect fills the store of sind ui with what Docker and the host know: the realms, clusters, nodes, networks and volumes, the mesh, the status of the clusters, the realm locks, the monitoring stacks and the host checks.
Package collect fills the store of sind ui with what Docker and the host know: the realms, clusters, nodes, networks and volumes, the mesh, the status of the clusters, the realm locks, the monitoring stacks and the host checks.
Package demo is the made-up Docker host that sind ui --demo shows: two realms with clusters of different shapes and states, a mesh, a monitoring stack, the host checks with one warning, and a few runs of the activity log.
Package demo is the made-up Docker host that sind ui --demo shows: two realms with clusters of different shapes and states, a mesh, a monitoring stack, the host checks with one warning, and a few runs of the activity log.
Package run starts the sind commands that the dialogs of sind ui make, and keeps their tasks in the store while they run.
Package run starts the sind commands that the dialogs of sind ui make, and keeps their tasks in the store while they run.
Package store holds what sind ui shows, in memory: the collectors write it, the pages and the live updates read it.
Package store holds what sind ui shows, in memory: the collectors write it, the pages and the live updates read it.

Jump to

Keyboard shortcuts

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