Documentation
¶
Overview ¶
Package admin provides an auto-generated administration panel for Nucleus, similar to Django's contrib.admin. It exposes a REST API for CRUD operations on registered models and serves an embedded SPA frontend.
Index ¶
- Constants
- func BrandingWarnings(b Branding) []string
- func EnsureBootstrapAdminUsersSchema(ctx context.Context, sqlDB *sql.DB, system string) error
- func NormalizePrefix(raw string) string
- func ParseImportData(reader io.Reader, format string) ([]map[string]interface{}, error)
- func ValidateActions(src datasource.DataSource, actions []ModelAction) error
- func ValidateBranding(b Branding) error
- func ValidateClientCode(c ClientCode) error
- func ValidateDashboards(src datasource.DataSource, widgets []Widget, dashboards []Dashboard) error
- func ValidateFieldWidgets(src datasource.DataSource, widgets map[string]string, client ClientCode) error
- func ValidateImportConfig(cfg ImportConfig, src datasource.DataSource) error
- func ValidateLocaleConfig(locale string, messages map[string]map[string]string) error
- func ValidatePages(pages []Page) error
- type ActionDownload
- type ActionField
- type ActionFieldType
- type ActionInput
- type ActionOption
- type ActionPlacement
- type ActionRequest
- type ActionResult
- type AdminAuth
- type AuditEntry
- type BootstrapAdminConfig
- type BootstrapAdminResult
- type Branding
- type Cache
- type ClientCode
- type Dashboard
- type DatabaseAdminAuth
- func (a *DatabaseAdminAuth) Authenticate(r *http.Request) (*auth.User, error)
- func (a *DatabaseAdminAuth) Authorize(user *auth.User, _ string, _ string) bool
- func (a *DatabaseAdminAuth) LoginHandler() http.Handler
- func (a *DatabaseAdminAuth) OperatorStore() *operatorStore
- func (a *DatabaseAdminAuth) WithAuthChain(chain *auth.Chain) *DatabaseAdminAuth
- func (a *DatabaseAdminAuth) WithBranding(b Branding) *DatabaseAdminAuth
- func (a *DatabaseAdminAuth) WithLocale(locale string) *DatabaseAdminAuth
- func (a *DatabaseAdminAuth) WithSystem(system string) *DatabaseAdminAuth
- func (a *DatabaseAdminAuth) WithTitle(title string) *DatabaseAdminAuth
- type DatabaseRuntimeInfo
- type DjangoFixtureRecord
- type DumpdataConfig
- type ExportConfig
- type ExportFormat
- type ExportResult
- type ImportConfig
- type ImportError
- type ImportReport
- type LoaddataConfig
- type ModelAction
- type Operator
- type Page
- type Palette
- type Panel
- func (p *Panel) Close(ctx context.Context) error
- func (p *Panel) ConsumeEventBus(eb nucleus.EventBus) func()
- func (p *Panel) ConsumeObservability(bus *observability.Bus) func()
- func (p *Panel) Dumpdata(ctx context.Context, cfg DumpdataConfig, targets []exportTarget) (ExportResult, error)
- func (p *Panel) EnableLiveClusterRelay() error
- func (p *Panel) ExecuteImport(c *router.Context, cfg ImportConfig, records []map[string]interface{}) (*ImportReport, error)
- func (p *Panel) FeatureFlag(name string) (enabled bool, ok bool)
- func (p *Panel) Handler() *router.Mux
- func (p *Panel) ImportFromFile(c *router.Context, storageKey string, cfg ImportConfig) (*ImportReport, error)
- func (p *Panel) LiveTrafficMiddleware() func(http.Handler) http.Handler
- func (p *Panel) Loaddata(c *router.Context, cfg LoaddataConfig) (*ImportReport, error)
- func (p *Panel) SetFeatureFlag(name string, enabled bool)
- func (p *Panel) SetSignalBus(bus *signals.Bus)
- type PanelConfig
- type RecordList
- type Series
- type SeriesValue
- type StatValue
- type TableValue
- type TenantContext
- type Widget
- type WidgetItem
- type WidgetValue
Constants ¶
const ( ThemeDark = "dark" ThemeLight = "light" ThemeSystem = "system" )
Themes an application may open the panel in. "system" follows the operator's system preference each time the panel opens.
const ( // WidgetKindValue reads Load: a value, a detail line or a short list. WidgetKindValue = "value" // WidgetKindStat reads Stat: a headline figure and its change. WidgetKindStat = "stat" // WidgetKindLine reads Series and draws it as a line chart. WidgetKindLine = "line" // WidgetKindBar reads Series and draws it as a bar chart. WidgetKindBar = "bar" // WidgetKindTable reads Table: columns and rows of text. WidgetKindTable = "table" // WidgetKindRecords reads Records: the newest rows of one model, which // the panel lists itself, as the operator who is looking. WidgetKindRecords = "records" )
The kinds of card the panel draws. An empty Kind is WidgetKindValue, the card A6 shipped.
const DefaultPrefix = "/admin"
const DefaultTitle = "Orbit"
DefaultTitle is the product name shown in the UI when no Title is configured. The panel is Orbit — it used to introduce itself as "Nucleus Admin", which left the product invisible in its own interface (OH-2/PR-ORB-01).
Variables ¶
This section is empty.
Functions ¶
func BrandingWarnings ¶ added in v1.19.0
BrandingWarnings lists what the panel will paint and does not keep its contrast, but starts anyway: a branding.primary_color that falls short in one theme. That key was accepted on any hex colour before the palette was checked per theme, and refusing a value that started yesterday would stop an application that changed nothing (QADR-0010); the warning names the theme and the per-theme key that fixes it. A failure that involves a per-theme key refuses to start instead (ValidateBranding).
func EnsureBootstrapAdminUsersSchema ¶
EnsureBootstrapAdminUsersSchema guarantees the admin users table exists WITHOUT inserting any user. orbit's mount calls it unconditionally, so the schema exists even when BootstrapPassword is empty and the operator provisions the admin account another way (e.g. `nucleus createuser`, whose own error message tells them to "start the app once to create the schema" — advice that used to be false, because the schema was only created when a bootstrap password was set, leaving the secure-default onboarding with no way in).
func NormalizePrefix ¶
NormalizePrefix canonicalizes the admin mount path.
func ParseImportData ¶
ParseImportData parses uploaded data and returns a slice of record maps.
func ValidateActions ¶ added in v1.10.0
func ValidateActions(src datasource.DataSource, actions []ModelAction) error
ValidateActions checks an application's declared actions against the data source they name, and is what turns a mistake in them into a refusal to start. orbit's module calls it before the panel is built; NewPanel repeats the compilation for callers that wire a panel by hand.
func ValidateBranding ¶ added in v1.10.0
ValidateBranding is validateBranding for the module wiring, which reports the error as a refusal to start.
func ValidateClientCode ¶ added in v1.19.0
func ValidateClientCode(c ClientCode) error
ValidateClientCode is loadClientCode for the module wiring, which reports the error as a refusal to start.
func ValidateDashboards ¶ added in v1.19.0
func ValidateDashboards(src datasource.DataSource, widgets []Widget, dashboards []Dashboard) error
ValidateDashboards checks the overview's widgets and the named dashboards against this application's models, for the module wiring, which reports the error as a refusal to start.
func ValidateFieldWidgets ¶ added in v1.19.0
func ValidateFieldWidgets(src datasource.DataSource, widgets map[string]string, client ClientCode) error
ValidateFieldWidgets refuses, at startup, a field_widgets entry the panel could never apply — the rule actions, pages, widgets, branding and the locale already follow.
Until it existed, field_widgets was the one declaration nothing checked: a widget the panel does not ship ("color" for "colour", "rich-text" for "richtext") or a key that names no field of the application (a typo, a renamed column, a model that was removed) started normally, and the schema published the field as its column type, as if nothing had been declared. Each of those entries never had an effect, so refusing it stops nothing that worked; it says, once and by name, what the operator would otherwise discover field by field in a form.
Two entries that name the same field with different widgets are refused too: declaredWidget takes the first spelling that matches, and when both spellings are the same one the choice follows map order, so the form could change between two requests.
A value may also name a field renderer the application declared (ClientCode.FieldRenderers, EXT-07): the check accepts exactly the names declared, so a renderer field_widgets names and no script was declared to register stops the application here, by name, rather than drawing the field the panel's way in silence.
func ValidateImportConfig ¶
func ValidateImportConfig(cfg ImportConfig, src datasource.DataSource) error
ValidateImportConfig checks import configuration.
func ValidateLocaleConfig ¶ added in v1.10.0
ValidateLocaleConfig is the module wiring's check for both halves.
func ValidatePages ¶ added in v1.10.0
ValidatePages is validatePages for the module wiring, which reports the error as a refusal to start.
Types ¶
type ActionDownload ¶ added in v1.19.0
type ActionDownload struct {
// Filename is the name the browser saves the file under. Only its last
// element is sent ("reports/q3.pdf" is sent as "q3.pdf"); a name that
// is empty, "." or "..", or holds a control character, is refused.
Filename string
// ContentType is the file's media type ("application/pdf",
// "text/csv; charset=utf-8"). It is required: the panel does not guess
// what a file is, and it tells the browser not to either.
ContentType string
// Body is the content. The panel reads it once, up to 32 MiB, and
// closes it when it is an io.Closer. A body larger than that is refused
// whole, never sent truncated: a file cut short is worse than no file,
// because it looks like one.
Body io.Reader
}
ActionDownload is a file an action hands the operator.
type ActionField ¶ added in v1.19.0
type ActionField struct {
// Name is the key the value travels under, on the wire and in
// ActionRequest.Input. It starts with a letter and holds letters,
// digits, '_' and '-', and is unique within the action.
Name string
// Label is what the form says next to the input. Empty falls back to
// Name.
Label string
// Type is what the operator enters. Empty means ActionFieldText; a type
// the panel does not know refuses to start.
Type ActionFieldType
// Required refuses the call when the value is missing or blank. On a
// boolean it means the box must be ticked ("I understand this cannot be
// undone").
Required bool
// Help is the one line a form shows under the input.
Help string
// Options are the choices of a select: the value posted and the label
// read. A select needs at least one; any other type may not have them.
Options []ActionOption
}
ActionField is one input an action asks for before it runs.
type ActionFieldType ¶ added in v1.19.0
type ActionFieldType string
ActionFieldType is what an action field asks for.
const ( // ActionFieldText is a line of text; it arrives as a string. ActionFieldText ActionFieldType = "text" // ActionFieldNumber is a number; it arrives as a float64. ActionFieldNumber ActionFieldType = "number" // ActionFieldBoolean is a yes/no; it arrives as a bool and is always // present, false when the operator left it unticked. ActionFieldBoolean ActionFieldType = "boolean" // ActionFieldSelect is one of the declared Options; it arrives as the // option's Value, a string. ActionFieldSelect ActionFieldType = "select" // ActionFieldDate is a calendar date, posted as YYYY-MM-DD; it arrives // as a time.Time at midnight UTC. ActionFieldDate ActionFieldType = "date" )
The types an action field may declare. Each one fixes the Go type the value arrives with in ActionRequest.Input.
type ActionInput ¶ added in v1.19.0
ActionInput is what the operator entered in an action's form, already checked against its Fields and typed by them: text and select as string, number as float64, boolean as bool, date as time.Time. A text, number, select or date field left empty is absent; a boolean is always present. It is nil for an action that declares no fields.
func (ActionInput) Bool ¶ added in v1.19.0
func (in ActionInput) Bool(name string) bool
Bool returns a boolean value; false when it is absent.
func (ActionInput) Date ¶ added in v1.19.0
func (in ActionInput) Date(name string) (time.Time, bool)
Date returns a date value and whether it was entered.
func (ActionInput) Number ¶ added in v1.19.0
func (in ActionInput) Number(name string) (float64, bool)
Number returns a number value and whether it was entered.
func (ActionInput) String ¶ added in v1.19.0
func (in ActionInput) String(name string) string
String returns a text or select value, or "" when it is absent.
type ActionOption ¶ added in v1.19.0
type ActionOption struct {
// Value is what is posted and what Run receives. Unique within the
// field and never empty.
Value string
// Label is what the operator reads. Empty falls back to Value.
Label string
}
ActionOption is one choice of a select field.
type ActionPlacement ¶ added in v1.19.0
type ActionPlacement string
ActionPlacement says where the panel offers an action.
const ( // ActionOnSelection offers the action over the grid's selection. It is // what the zero value means, so an action declared before placements // existed is offered exactly where it was. ActionOnSelection ActionPlacement = "selection" // ActionOnRecord offers the action on one record: in its record view // and in its row's menu. The action receives exactly that record's id. ActionOnRecord ActionPlacement = "record" // ActionOnSelectionAndRecord offers the action in both places. ActionOnSelectionAndRecord ActionPlacement = "selection_and_record" )
The places an action can be offered.
type ActionRequest ¶ added in v1.10.0
type ActionRequest struct {
// Model is the model name the action was invoked on.
Model string
// IDs are the selected rows, in the order the client sent them, after
// tenant and row-ownership confinement. Empty only for an action that
// declared AllowEmptySelection.
IDs []string
// Actor is the operator's username, as the audit trail records it.
Actor string
// Tenant is the tenant in force for the request, empty when the panel
// is not multi-tenant.
Tenant string
// Database is the alias of the database the grid was reading, so an
// action on a model that lives on another handle writes where it read.
Database string
// Input is what the operator entered in the action's form, checked
// against its Fields and typed by them. Nil for an action that declares
// no fields.
Input ActionInput
}
ActionRequest is what an action is told about the call.
type ActionResult ¶ added in v1.10.0
type ActionResult struct {
// Message is shown to the operator ("3 posts published"). It is shown
// with a message and with a redirect; a download's answer is the file.
Message string
// Affected is how many rows the action changed, for the audit entry and
// the toast. It is the action's own count, not the size of the
// selection.
Affected int
// Data carries anything else the UI should get (a summary). It is
// echoed in a message or redirect answer and NOT audited: an action
// decides what it returns to the screen, the trail keeps the fact that
// it ran.
Data map[string]any
// Redirect is a page of the panel to take the operator to after the
// action ran: "/data-studio?model=Invoice&record=42", or
// "/x/reports/batch/7" for a screen of the application's own. It is a
// path relative to the panel's root, never a URL: an absolute URL, a
// scheme, a host, a "//" start, a backslash, a control character or a
// "." or ".." segment is refused when the action answers, because a
// redirect an operator's input can steer is how a panel becomes an
// open redirect.
Redirect string
// Download is a file the action produced, sent to the operator as an
// attachment. The panel sends the bytes the action hands it and
// nothing else: it never opens a path, so there is no file it can be
// told to read.
Download *ActionDownload
}
ActionResult is what an action reports back. Everything in it is optional: an action that only needs to say "done" returns the zero value.
An action answers in one of three ways. With neither Redirect nor Download it answers with a message, as every action did before it could do anything else. With Redirect it takes the operator to a page of the panel; with Download it hands them a file. It may not set both: the panel refuses that answer, and the operator is told the action ran and its answer could not be sent.
type AdminAuth ¶
type AdminAuth interface {
Authenticate(r *http.Request) (*auth.User, error)
Authorize(user *auth.User, model string, action string) bool
LoginHandler() http.Handler
}
AdminAuth is the interface for admin panel authentication and authorization.
type AuditEntry ¶
type AuditEntry struct {
ID uint `json:"id"`
UserID string `json:"user_id"`
Username string `json:"username"`
Action string `json:"action"`
ModelName string `json:"model_name"` // Model or surface affected (e.g. "User", "rbac", "feature_flag")
RecordID string `json:"record_id"` // ID of the affected record (or key / name of the affected object)
OldValue map[string]any `json:"old_value"` // Previous state (updates, deletes, removals) — redacted
NewValue map[string]any `json:"new_value"` // New state or outcome (creates, updates, management actions) — redacted
IP string `json:"ip"`
UserAgent string `json:"user_agent"`
CreatedAt time.Time `json:"created_at"`
}
AuditEntry represents a single audit log record.
Every mutating handler of the panel records its own entry (see audit_coverage_test.go for the route-by-route contract). Action is the verb: Data Studio uses create/update/delete/bulk_delete/bulk_export and schema.update; the management surfaces use dotted names (rbac.policy.add, flag.set, migration.apply, cache.flush, export.create, import.execute, live.exclude.add, audit.clear, ...); the session surfaces use login, login.failed, login.locked, logout and session.terminate.
type BootstrapAdminConfig ¶
type BootstrapAdminConfig struct {
Username string
Email string
Password string
// System is the database dialect of the target connection, as
// reported by `db.DB.System()` ("sqlite", "postgresql", "mysql",
// "mssql", "oracle"). It selects the dialect-appropriate
// CREATE-TABLE form for the admin users table. An empty System
// falls back to the portable `CREATE TABLE IF NOT EXISTS` form
// (accepted by SQLite, PostgreSQL, and MySQL) — preserving the
// pre-dialect-aware behaviour for any caller that does not set it.
System string
}
BootstrapAdminConfig defines how the framework should initialize the first admin account when the admin users table is empty.
type BootstrapAdminResult ¶
type BootstrapAdminResult struct {
Created bool
Username string
Password string
PasswordGenerated bool
}
BootstrapAdminResult reports whether a bootstrap admin account was created. Password is only populated when generated by the framework.
func EnsureBootstrapAdminUser ¶
func EnsureBootstrapAdminUser(ctx context.Context, sqlDB *sql.DB, cfg BootstrapAdminConfig) (BootstrapAdminResult, error)
EnsureBootstrapAdminUser guarantees the admin users table exists and creates one default superuser if the table is currently empty.
type Branding ¶ added in v1.10.0
type Branding struct {
// LogoURL is the image shown in the sidebar and on the login screen. It
// is a URL the BROWSER fetches, so it is either absolute (https://…) or
// a path the application already serves ("/static/logo.svg"); the panel
// does not become a file server for it. An absolute URL's origin is added
// to the img-src of the panel's Content-Security-Policy, so the browser
// loads what the configuration accepted.
LogoURL string `yaml:"logo_url" koanf:"logo_url"`
// FaviconURL replaces the icon in the browser tab, same rules.
FaviconURL string `yaml:"favicon_url" koanf:"favicon_url"`
// PrimaryColor is the accent colour, as a CSS hex colour (#0b5fff).
// It lands in a custom property the stylesheet already reads, so it
// colours the buttons, the active navigation entry and the focus ring
// together rather than one of them.
PrimaryColor string `yaml:"primary_color" koanf:"primary_color"`
// Theme is the theme the panel opens in before an operator has chosen
// one: "dark", "light", or "system" for the operator's system
// preference. It decides the first frame — the document applies it
// before the bundle runs — and an operator who uses the panel's toggle
// keeps their choice over it. Empty keeps the panel's own behaviour:
// the operator's last theme, or else the browser's preference
// (appearance.go).
Theme string `yaml:"theme" koanf:"theme"`
// Light and Dark are the palette of each theme: the accent, the
// surface and the text. Each colour is checked at startup against the
// ground it is drawn on in THAT theme, and one that falls short of the
// contrast it needs refuses to start, naming the theme and the key.
Light Palette `yaml:"light" koanf:"light"`
Dark Palette `yaml:"dark" koanf:"dark"`
}
Branding is what an application says about how the panel should look. Every field is optional; an empty one keeps Orbit's own.
type Cache ¶ added in v1.10.0
type Cache interface {
// CacheName labels the cache in the view ("redis", "in-process", the
// name of a shared cluster). It is shown to an operator, so it should
// identify WHICH cache, not restate its type.
CacheName() string
// CacheEntries returns how many entries the cache holds. known=false
// means the backend cannot answer; the view then shows the cache
// without a count instead of showing zero, which would read as empty.
CacheEntries(ctx context.Context) (count int64, known bool, err error)
// FlushCache empties the cache and returns how many entries went, or -1
// when the backend cannot say. It is the destructive half of the
// contract: the panel audits every call.
FlushCache(ctx context.Context) (removed int64, err error)
}
Cache is the cache an application declares to the panel, so the cache view reports — and the flush button empties — the cache the application actually has (OR-49).
It exists because there is nothing for the panel to discover. Nucleus ships pkg/cache, but nothing in the framework wires one into an application: a cache is built, owned and handed around by the application itself, so the application is the only thing that can say which one the panel is looking at. Before this contract the view knew a single cache — a Redis URL passed in configuration — and answered every other application "redis url is not configured", including the many that have no Redis at all and never asked for one.
The panel neither reads nor writes entries: it counts them and empties them, which is the whole of what an operator does to a cache from a screen. An implementation that cannot count says so through known=false rather than guessing a number.
type ClientCode ¶ added in v1.19.0
type ClientCode struct {
// Files holds the scripts and stylesheets — typically an embed.FS of
// the application's, or os.DirFS. The panel reads the declared files
// once, when it mounts, and serves those bytes: a file that changes on
// disk afterwards is not what the panel serves until it restarts.
Files fs.FS
// Scripts are the paths, inside Files, of the JavaScript the panel's
// document loads after the panel's own bundle, in this order. Each is a
// classic script, deferred, so it runs once the bundle has set up
// window.orbit. Inline script stays refused by the panel's policy.
Scripts []string
// Stylesheets are the paths, inside Files, of the stylesheets the
// panel's document links after its own.
Stylesheets []string
// FieldRenderers are the names of the field renderers the scripts
// register (window.orbit.registerFieldRenderer). A field_widgets entry
// may name one of them instead of a widget the panel ships; the panel
// then draws that field with it in the list and on the record view, and
// falls back to its own drawing when the renderer fails.
FieldRenderers []string
}
ClientCode is the application's own code for the browser side of the panel: scripts and stylesheets read from Files, and the names of the field renderers those scripts register. Every field is optional; with nothing declared, the panel's document is the one it served before.
type Dashboard ¶ added in v1.19.0
type Dashboard struct {
// ID is the path segment it is served under (<prefix>/dashboards/<id>)
// and the end of its RBAC resource (admin:dashboard:<id>). Lowercase
// letters, digits and dashes.
ID string
// Title is what the navigation entry and the screen's heading read.
Title string
// Description is the one line under the heading.
Description string
// Permission is the RBAC action required on admin:dashboard:<id>. Empty
// means "view". An operator without it does not see the dashboard in
// the navigation, and its API answers them 403. A superuser always
// passes, as everywhere else in the panel.
Permission string
// Columns is how many columns its grid has on a wide screen, from 1 to
// 4. Zero is 4, the overview's.
Columns int
// Widgets are its cards, drawn in the order they are declared — the
// order and each card's Span are the layout. Each card's own
// Permission is an action on admin:dashboard:<id>. A dashboard with no
// cards is a blank screen, and refuses to start.
Widgets []Widget
}
Dashboard is a screen of cards an application adds beside the overview.
type DatabaseAdminAuth ¶
type DatabaseAdminAuth struct {
// contains filtered or unexported fields
}
DatabaseAdminAuth is the default admin auth provider wired by pkg/app. Behavior: - Admin is always protected: login is required.
func NewDatabaseAdminAuth ¶
func NewDatabaseAdminAuth(sqlDB *sql.DB, session *auth.SessionManager, prefix string) *DatabaseAdminAuth
func (*DatabaseAdminAuth) Authenticate ¶
Authenticate returns an authenticated admin user from server-side session.
func (*DatabaseAdminAuth) Authorize ¶
Authorize currently allows all actions for authenticated admin users.
func (*DatabaseAdminAuth) LoginHandler ¶
func (a *DatabaseAdminAuth) LoginHandler() http.Handler
LoginHandler renders the login page (GET) and validates credentials (POST).
func (*DatabaseAdminAuth) OperatorStore ¶ added in v1.10.0
func (a *DatabaseAdminAuth) OperatorStore() *operatorStore
OperatorStore exposes the admin-users table to the panel's operator routes.
func (*DatabaseAdminAuth) WithAuthChain ¶
func (a *DatabaseAdminAuth) WithAuthChain(chain *auth.Chain) *DatabaseAdminAuth
NewDatabaseAdminAuth creates a DB-backed AdminAuth provider that validates credentials against nucleus_admin_users (same table used by createuser). WithAuthChain delegates credential verification to the application's declared authentication chain (auth_backends), so an operator who configured a corporate directory gets directory login in the admin panel without orbit shipping an LDAP client.
It delegates AUTHENTICATION only. Authorization stays here: a directory user who is not in the admin table is refused. Skipping that would turn an LDAP integration into a privilege escalation — every employee in the company would become an administrator of this panel.
func (*DatabaseAdminAuth) WithBranding ¶ added in v1.10.0
func (a *DatabaseAdminAuth) WithBranding(b Branding) *DatabaseAdminAuth
WithBranding gives the login page the application's logo, colour and favicon. Returns the receiver for chaining.
The branding is validated and normalised the way the panel's is, and one that does not validate is ignored here as the panel ignores it: the login screen and the panel behind it wear the same clothes.
func (*DatabaseAdminAuth) WithLocale ¶ added in v1.10.0
func (a *DatabaseAdminAuth) WithLocale(locale string) *DatabaseAdminAuth
WithLocale gives the login page the language the panel opens in.
func (*DatabaseAdminAuth) WithSystem ¶
func (a *DatabaseAdminAuth) WithSystem(system string) *DatabaseAdminAuth
WithSystem names the SQL dialect of the admin database so that the user lookups Authenticate and the login run on every request are bounded queries (WHERE id = ? / WHERE LOWER(username) = LOWER(?) OR ...) instead of a full read of the admin table followed by a linear scan. orbit.go passes db.DB.System() of the auth database. A caller that leaves it unset keeps the full-read path, which needs no placeholder style.
func (*DatabaseAdminAuth) WithTitle ¶
func (a *DatabaseAdminAuth) WithTitle(title string) *DatabaseAdminAuth
WithTitle sets the heading the login page renders — the panel's configured Title. Returns the receiver for chaining, like WithAuthChain.
type DatabaseRuntimeInfo ¶
type DatabaseRuntimeInfo struct {
Alias string `json:"alias"`
Engine string `json:"engine"`
Dialect string `json:"dialect"`
IsDefault bool `json:"is_default"`
}
DatabaseRuntimeInfo describes one configured DB alias for admin observability.
type DjangoFixtureRecord ¶
type DjangoFixtureRecord struct {
Model string `json:"model"`
PK interface{} `json:"pk"`
Fields map[string]interface{} `json:"fields"`
}
DjangoFixtureRecord represents a single record in Django-style fixture format. Format: {"model": "app.ModelName", "pk": 1, "fields": {...}}
type DumpdataConfig ¶
type DumpdataConfig struct {
Models []string `json:"models"` // Models to export (empty = every one the operator may list)
Database string `json:"database"` // Source database alias
TenantID string `json:"tenant_id"` // Tenant scope (empty = all)
}
DumpdataConfig configures the dumpdata operation.
type ExportConfig ¶
type ExportConfig struct {
Models []string `json:"models"` // Models to export (empty = every one the operator may list)
Database string `json:"database"` // Source database alias
TenantID string `json:"tenant_id"` // Tenant scope (empty = all)
Format ExportFormat `json:"format"` // csv | json | sql
Filters map[string]string `json:"filters"` // Additional filters (model.field=value)
}
ExportConfig defines the scope and format of an export operation.
type ExportFormat ¶
type ExportFormat string
ExportFormat defines supported export formats.
const ( ExportFormatCSV ExportFormat = "csv" ExportFormatJSON ExportFormat = "json" ExportFormatSQL ExportFormat = "sql" )
type ExportResult ¶
type ExportResult struct {
ID string `json:"id"`
Status string `json:"status"` // completed, processing, failed
Format string `json:"format"`
Tenant string `json:"tenant,omitempty"` // tenant the export was confined to ("" = every tenant)
Filename string `json:"filename"`
StorageKey string `json:"storage_key"` // Key in storage for download
Size int64 `json:"size"`
Records int `json:"records"`
Error string `json:"error,omitempty"`
CreatedAt time.Time `json:"created_at"`
URL string `json:"url,omitempty"` // Download URL when available
// contains filtered or unexported fields
}
ExportResult holds the result of an export operation.
type ImportConfig ¶
type ImportConfig struct {
Database string `json:"database"` // Target database alias
TenantID string `json:"tenant_id"` // Target tenant (for tenant field injection)
Model string `json:"model"` // Target model
Format string `json:"format"` // csv | json
OnConflict string `json:"on_conflict"` // skip | update | error
DryRun bool `json:"dry_run"` // Validate only, no changes
BatchSize int `json:"batch_size"` // Records per batch (default 100)
}
ImportConfig defines the target and behavior of an import.
type ImportError ¶
type ImportError struct {
Row int `json:"row"`
Field string `json:"field,omitempty"`
Message string `json:"message"`
}
ImportError describes a single row import error. Row is the row's position in the file, counted from 0.
func ValidateImportData ¶
func ValidateImportData(mi datasource.ModelInfo, records []map[string]interface{}, tenantID string) []ImportError
ValidateImportData validates records against model schema without importing.
type ImportReport ¶
type ImportReport struct {
Total int `json:"total"`
Imported int `json:"imported"`
Skipped int `json:"skipped"`
Updated int `json:"updated"`
Failed int `json:"failed"`
Errors []ImportError `json:"errors"`
DryRun bool `json:"dry_run"`
}
ImportReport summarizes import results.
type LoaddataConfig ¶
type LoaddataConfig struct {
StorageKey string `json:"key"` // Storage key of the fixture file
OnConflict string `json:"on_conflict"` // "skip" (default) or "update"
Database string `json:"database"` // Target database alias
TenantID string `json:"tenant_id"` // Tenant ID for auto-injection
}
LoaddataConfig configures the loaddata operation.
type ModelAction ¶ added in v1.10.0
type ModelAction struct {
// Name is the verb on the wire and the RBAC action it is authorized
// under: a policy reads `p, editors, admin:Post, publish`. It must be
// unique per model and may not shadow a verb the panel already has.
Name string
// Model is the model the action belongs to, by its registry name
// ("Post"). An unknown model fails at startup rather than leaving the
// action invisible for the life of the process.
Model string
// Label is what the button says ("Publish"). Empty falls back to Name.
Label string
// Description is the one-line explanation a UI can show next to it.
Description string
// Confirm, when set, is the question the UI asks before running. It is
// a rendering hint: the panel does not enforce it, because a client
// that skips the dialog is the same client that could call the
// endpoint directly.
Confirm string
// Destructive marks an action that changes or removes data. It makes
// the UI treat the button as dangerous, and it makes the action refuse
// a read-only model, which is what read-only means.
Destructive bool
// AllowEmptySelection lets the action run with no rows selected, for
// the ones whose subject is the table and not a selection ("rebuild the
// index"). The zero value requires a selection, which is what a button
// on a grid means. An action offered only on a record always has one,
// so declaring both refuses to start.
AllowEmptySelection bool
// Placement is where the panel offers the action: on the grid's
// selection (ActionOnSelection, the zero value and what every action
// did before it could say), on one record — its record view and its
// row's menu — (ActionOnRecord), or on both
// (ActionOnSelectionAndRecord). It is enforced, not only drawn: an
// action offered only on a record is refused at the bulk endpoint, and
// one offered only on a selection at the record endpoint.
Placement ActionPlacement
// Fields are the inputs the action asks for before it runs — the
// reason for a refund, the date to publish on. The UI draws them as a
// form in place of the plain confirmation; the panel checks what comes
// back against them and refuses the call, naming the field, before Run
// is called; Run reads the values, already typed, from
// ActionRequest.Input. An action without fields runs exactly as one
// did before actions could ask.
Fields []ActionField
// Run performs the action. Returning an error refuses it: the message
// reaches the operator, so it should say what a person can do about it.
Run func(ctx context.Context, req ActionRequest) (ActionResult, error)
}
ModelAction is one action an application defines for one of its models.
Run receives the ids the operator selected, already confined to what that operator may touch: a row of another tenant, or one owned by somebody else when the grant is admin:<Model>#own, never reaches it. That confinement is the reason the action goes through the panel at all instead of being an endpoint of the application's own: an action that bypassed it would be the way around every row policy the panel enforces.
type Operator ¶ added in v1.10.0
Operator is who is looking at an application's page: enough to greet them, scope what the page shows and write the application's own log line. It is a copy, so a page cannot change the session by writing to it.
func OperatorFromContext ¶ added in v1.10.0
OperatorFromContext returns the panel operator the request was authenticated as. ok is false on a panel with no auth provider (the development posture of ADR-016), which is the only way a page is reached by nobody.
type Page ¶ added in v1.10.0
type Page struct {
// ID is the path segment the page is served under (<prefix>/x/<id>/)
// and the key the navigation uses. Lowercase letters, digits and
// dashes: it is a URL, not a title.
ID string
// Title is what the navigation entry reads.
Title string
// Description is the one line a UI can show under the title.
Description string
// Icon names an icon the SPA already ships, as the model screens do.
// Unknown or empty falls back to a default.
Icon string
// Permission is the RBAC action required on resource admin:page:<id>.
// Empty means "view". A superuser always passes, as everywhere else in
// the panel.
Permission string
// Handler serves the page. It receives the request with the panel's
// prefix already stripped ("/" is the page's own root) and with the
// operator in its context — see OperatorFromContext.
Handler http.Handler
}
Screens an application adds to the panel (CUST-04).
The panel's screens are the ones every application has. A product always grows one that is only its own — a reconciliation report, a switchboard for a batch nobody else runs — and until now the only extension point was DataSource, which replaces the backend and leaves the interface alone.
A page is an ordinary http.Handler the application writes, mounted INSIDE the panel: under the panel's prefix, behind the panel's session, gated by the panel's RBAC, listed in the panel's navigation. That is the whole of what it buys — the application still writes the page. What it saves is everything around it: an application that served the same handler from its own router would have to re-implement the sign-in, the authorization and the link.
It is a link and not a frame on purpose. The panel sends X-Frame-Options: DENY and frame-ancestors 'none' on every response, so a page embedded in the SPA would be blocked by the browser while every Go test still read a 200 — and relaxing that header for the whole panel to embed one screen trades a clickjacking defence for a layout. The same hardening applies to the page's own response: its scripts come from files, not from inline <script> (script-src 'self').
type Palette ¶ added in v1.19.0
type Palette struct {
// PrimaryColor is the accent in this theme: the buttons, the active
// navigation entry and the focus ring. It overrides
// Branding.PrimaryColor in this theme only.
PrimaryColor string `yaml:"primary_color" koanf:"primary_color"`
// SurfaceColor is the ground the panel is drawn on: the page, the
// cards and the menus.
SurfaceColor string `yaml:"surface_color" koanf:"surface_color"`
// TextColor is the text drawn on that ground.
TextColor string `yaml:"text_color" koanf:"text_color"`
}
Palette is the colours of one theme. Every field is optional and is a CSS hex colour (#0b5fff or #05f); an empty one keeps the panel's own.
type Panel ¶
type Panel struct {
// contains filtered or unexported fields
}
Panel is the admin panel instance that provides CRUD UI for registered models.
func NewPanel ¶
func NewPanel(src datasource.DataSource, logger *slog.Logger, cfg PanelConfig) *Panel
NewPanel creates a new admin panel. Data Studio reads and writes records through the neutral datasource contract (ADR-001); the Nucleus-backed adapter is built by the caller (orbit.go) from the same Runtime accessors and passed in as src. The panel no longer imports the model registry for record access — only the optional cfg.SchemaRegistry, for the field-metadata editor.
func (*Panel) ConsumeEventBus ¶
ConsumeEventBus wires the live SQL and HTTP feeds to the framework's first-party EventBus (nucleus.Runtime.Observability()) — the orbit counterpart to ConsumeObservability, which takes the experimental *observability.Bus directly (SQL only). It subscribes to SQL and HTTP events, drains them into the live ring buffers + stream, and returns a stop function (also invoked from Close) that cancels both subscriptions.
The HTTP lane is what makes host-application traffic reach the in-process panel: the framework's app-level HTTP middleware emits an HTTPEvent for every request, so the panel no longer depends on the host mounting LiveTrafficMiddleware (an internal type the module API cannot expose). Events whose path falls under the admin prefix are skipped here — the panel's own middleware lane records those (and only those), so a request is never recorded twice; live_exclude_patterns apply the same way they do in the middleware and the cluster relay ingest.
The EventBus hands back detached value events and owns the underlying bus's pooled-event Release discipline internally, so these drains are plain (no Release, no buffered-event drain on cancel — cancel() closes the channels). Safe no-op when p, p.live, or eb is nil.
func (*Panel) ConsumeObservability ¶
func (p *Panel) ConsumeObservability(bus *observability.Bus) func()
ConsumeObservability wires the live view's SQL feed to the application observability bus. The bus receives EVERY model.CRUD query across the whole application — the framework's default SQL observer (installed in pkg/app) emits to it — not just the queries issued by the admin's own Data Studio CRUDs. This is the "bus becomes the single SQL feed" step: application queries (REST resources, app-side CRUD) now surface in the live view, which previously only saw the admin panel's own browsing.
It marks the panel as bus-connected so getCRUD skips the now-redundant per-CRUD observer (avoiding double-recording), starts a goroutine draining the subscription into the SQL ring buffer + live stream, and returns a stop function (also invoked from Close). Safe no-op when p, p.live, or bus is nil.
func (*Panel) Dumpdata ¶
func (p *Panel) Dumpdata(ctx context.Context, cfg DumpdataConfig, targets []exportTarget) (ExportResult, error)
Dumpdata exports the targets (exportTargets) to a Django-compatible JSON fixture file. Each record is serialized as {"model": "AppName.ModelName", "pk": <id>, "fields": {...}}, and carries the rows and fields its target's read scope lets the requesting operator see; a model with no target is not dumped.
func (*Panel) EnableLiveClusterRelay ¶
EnableLiveClusterRelay enables cluster-aware live telemetry distribution. It is optional and safe to call multiple times.
func (*Panel) ExecuteImport ¶
func (p *Panel) ExecuteImport(c *router.Context, cfg ImportConfig, records []map[string]interface{}) (*ImportReport, error)
ExecuteImport writes already-parsed records into cfg.Model for c's operator: it plans the file (planImport), refusing it whole when one row is not one the operator may write, and then writes the plan — unless cfg.DryRun, which stops after the plan. It does not validate the cells: ImportFromFile does, between the two.
func (*Panel) FeatureFlag ¶
FeatureFlag returns one in-memory feature flag value.
func (*Panel) Handler ¶
Handler returns a *router.Mux that can be mounted on the application router.
func (*Panel) ImportFromFile ¶
func (p *Panel) ImportFromFile(c *router.Context, storageKey string, cfg ImportConfig) (*ImportReport, error)
ImportFromFile is the import of an uploaded file for c's operator, the validate step (cfg.DryRun) and the execute step alike: read and parse the file, plan it (planImport), which refuses it whole when one row is not one the operator may write, validate its cells, and write the plan unless the cells fail or cfg.DryRun. Both steps take the same path up to the write, so the validate step refuses what the execute step would.
func (*Panel) LiveTrafficMiddleware ¶
LiveTrafficMiddleware returns non-blocking runtime observation middleware that records requests into the live feed. In a framework-wired deployment it is NOT the lane host-application traffic arrives on: ConsumeEventBus drains the framework's HTTP events (emitted by the app-level middleware), so mounting this at app level is unnecessary there — the panel keeps it on its own SPA branch, where it also records session activity (which the bus event does not carry). It remains useful for hand-wired panels that have no nucleus.EventBus to consume.
func (*Panel) Loaddata ¶
func (p *Panel) Loaddata(c *router.Context, cfg LoaddataConfig) (*ImportReport, error)
Loaddata imports data from a Django-compatible JSON fixture file for c's operator. It auto-detects models from the "model" field, skips unknown models, and handles conflicts based on the OnConflict setting.
It is the import in another format, and writes the way the import does (OR-67): every record of the fixture is planned before any is written — a record whose pk the store holds is an update (or a skip), any other a create — and each asks what the record form asks (planLoad). One record the operator may not write refuses the whole fixture with importRefused.
func (*Panel) SetFeatureFlag ¶
SetFeatureFlag upserts one in-memory feature flag value.
func (*Panel) SetSignalBus ¶
SetSignalBus sets the signal bus for CRUD operations.
type PanelConfig ¶
type PanelConfig struct {
Prefix string // URL prefix (default "/admin")
Title string // Site title shown in the UI
Environment string
OTLPEndpoint string // optional OTLP endpoint configured by the host app
RedisURL string // optional Redis URL for background jobs runtime snapshot
// Cache is the cache the application declared, or nil. See the Cache
// interface in runtime_cache.go: nothing in the framework owns an
// application's cache, so the panel can only show the one it is handed.
Cache Cache
TaskInspector tasks.Inspector // optional configured queue inspector
LiveExcludePatterns []string // optional path patterns excluded from live HTTP capture
LiveClusterEnabled bool // when true, publish/subscribe live telemetry through Redis
LiveClusterRedisURL string // optional Redis URL for live cluster relay (falls back to RedisURL)
LiveClusterChannel string // optional pub/sub channel (default nucleus:admin:live:v1)
LiveClusterNodeID string // optional explicit node id (defaults to runtime identity)
LiveClusterToken string // optional shared token to reject untrusted relay messages
TraceURLTemplate string // optional trace explorer URL template (supports {trace_id})
Databases []DatabaseRuntimeInfo
DatabaseHandles map[string]*db.DB // optional alias->db handle mapping for runtime stats
EnvironmentSnapshot []string // optional env snapshot (defaults to os.Environ at startup)
FeatureFlags map[string]bool // optional initial in-memory feature flags
MailDriver string
MailFrom string
SMTPHost string
// Mailer and Outbox are the DELIVERY half of the email view (OR-50):
// the sender it asks whether it can deliver, and the queue mail waits
// in. Both come from the framework runtime and both may be nil — an
// application can run without either.
Mailer mail.Sender
Outbox *outbox.ManagedOutbox
Auth AdminAuth
Session *auth.SessionManager // optional session manager for admin telemetry
SessionStore string // configured session store label (memory|sql|redis)
SessionRuntime auth.SessionRuntimeIdentity
// Multi-tenant configuration. When enabled, Data Studio is confined to
// the tenant of each request — list, get, create, update, delete, bulk,
// CSV export, exports (and their job list, status and download),
// imports and fixtures — resolved by TenantResolver (the host
// application's request scope) and falling back to MultiTenantDefault.
// A request that resolves no tenant is refused (403) unless its operator
// may switch tenants; it does not fall back to every tenant. Only a
// superuser, or a subject granted the tenant_switch RBAC action on
// admin:*, may switch the request to another tenant or to all of them
// with ?tenant=; every switch is audited. The confinement trusts the
// resolver: a tenant read from a header the client controls is the
// client's choice, not the host's — except for an operator whose
// account names a tenant (OR-80): one who may not switch is confined to
// it, and a request that resolves another tenant is refused. An
// operator with no tenant follows the resolver, with a WARN once per
// process, until v2.0.0 refuses them (DEP-2026-003).
MultiTenantEnabled bool // whether multi-tenant mode is active
MultiTenantDefault string // default tenant ID when none resolved
MultiTenantAutoFilter bool // confine Data Studio to the request's tenant (default true when multi-tenant enabled)
MultiTenantField string // override tenant field name (empty = auto-detect from model)
MultiTenantIDs []string // known tenant IDs for the selector UI (empty = discover from scope)
// TenantResolver returns the tenant the host application resolved for the
// request (nucleus resolves it from the subdomain or a header before the
// panel runs). Nil means no host resolution: the default tenant applies.
TenantResolver func(*http.Request) (tenant string, ok bool)
MultiSiteEnabled bool // whether multi-site mode is active
MultiSiteDefault string // default site name
MultiSiteNames []string // known site names for the selector UI
// RBAC configuration
RBACEnforcer *authz.Enforcer // optional Casbin enforcer for fine-grained authorization
// Row ownership. RowOwnerFields maps a model name to the column that
// says which operator a row belongs to, with "*" as the default for
// every model that carries the same column. It is what makes a policy on
// admin:<Model>#own enforceable: list is filtered by it, a row that
// belongs to somebody else is reported as not found, and a create stamps
// it. A #own grant on a model with no entry here is REFUSED, never
// widened to every row.
//
// RowOwnerSubject picks which name of the operator the column holds:
// "username" (default) or "id".
RowOwnerFields map[string]string
RowOwnerSubject string
// FieldWidgets declares how a field is edited when its type cannot say:
// "Model.Field" (or "Model.column") to one of json, richtext, file or
// image. A JSON document is inferred from the type and needs no entry;
// "this string is HTML" and "this string is a storage key" are claims
// about intent that no type carries, so they are declared here.
FieldWidgets map[string]string
// Actions and Pages are what an application adds to the panel that the
// panel cannot discover: a verb for one of its own models
// (actions_custom.go) and a screen of its own (pages_custom.go). Both
// are validated before the panel serves — a typo in either is a button
// or a link that would otherwise just never appear.
Actions []ModelAction
Pages []Page
// Branding, Widgets, Locale and Messages are how an application wears
// its own clothes: the logo and colour on every page (branding.go), the
// cards its overview opens on (dashboard.go), and the language the
// chrome speaks (i18n.go). Branding and Locale are plain values and
// bind from configuration; the widgets carry functions and do not.
Branding Branding
Widgets []Widget
Locale string
Messages map[string]map[string]string
// Dashboards are screens of cards beside the overview, each behind its
// own permission (dashboards.go).
Dashboards []Dashboard
// Client is the application's own code for the browser side of the
// panel: scripts and stylesheets the document loads after the bundle,
// and the field renderers those scripts register (client_code.go).
Client ClientCode
// Audit logging configuration
AuditEnabled bool // whether audit logging is enabled
AuditMaxSize int // max audit entries in memory (default 10000)
// AuditStore selects where the trail is kept: "database" (the default
// when the panel has a database handle) writes a table the panel owns,
// so the trail survives the process and is shared by every replica;
// "memory" keeps the process-lifetime ring, which is what the panel had
// before and what a panel with no handle gets either way.
AuditStore string
// AuditRetentionDays drops entries older than that many days. Zero keeps
// them until somebody clears the log; the ring's own bound
// (AuditMaxSize) is a COUNT and answers a different question.
AuditRetentionDays int
// Migrations path
MigrationsPath string // path to migration files directory
// Storage for exports/imports
Store storage.Store
// SchemaRegistry is an optional Nucleus model registry used ONLY by the
// runtime field-metadata editor (handleUpdateFieldMeta), which mutates model
// metadata and has no equivalent in the neutral datasource contract. Data
// Studio CRUD does not use it — it speaks datasource.DataSource (ADR-001).
SchemaRegistry *model.Registry
}
PanelConfig configures the admin panel.
type RecordList ¶ added in v1.19.0
type RecordList struct {
// Model is the model whose rows are listed. Required.
Model string
// Fields are the columns shown, by Go name or column. Empty is the
// model's list fields, or else its first three.
Fields []string
// OrderBy is the order, in the grid's syntax: "created_at desc". Empty
// is newest first — by created_at when the model has one, else by its
// primary key. An operator who does not read the field it orders by
// is not shown the card: the rows in that order are what the field
// holds, ranked.
OrderBy string
// Limit is how many rows: zero is 5, and at most 50.
Limit int
}
RecordList is what a "records" card lists: the newest rows of one of the application's models.
type Series ¶ added in v1.19.0
type Series struct {
// Name is the legend's label. It may be empty when the chart has one
// series and its title says what it counts.
Name string
// Values are the readings, one per label of the SeriesValue. A value
// that is not a finite number cannot be drawn.
Values []float64
}
Series is one named sequence of a chart.
type SeriesValue ¶ added in v1.19.0
type SeriesValue struct {
// Labels are the points of the horizontal axis, in order — days, hours,
// categories — formatted by the application.
Labels []string
// Series are the lines, or the bars of each label. Every one carries
// exactly one value per label.
Series []Series
// Detail is a line under the chart.
Detail string
}
SeriesValue is what a "line" or "bar" card draws: one value per label for each series.
type StatValue ¶ added in v1.19.0
type StatValue struct {
// Value is the headline, formatted by the application.
Value string
// Detail is the smaller line under it.
Detail string
// Delta is the change, as the application formats it ("+12%",
// "-3 since yesterday"). Empty draws no change.
Delta string
// Trend is which way the change goes: "up", "down" or "flat". It is
// what the arrow draws and what a screen reader says. Empty draws the
// delta with no arrow.
Trend string
// Sentiment says whether the change is good news: "good", "bad", or
// empty for neither. Up is not always good — failed payments going up
// is the reason a card exists — so the direction does not decide it.
Sentiment string
}
StatValue is what a "stat" card shows: a figure, and how it moved.
type TableValue ¶ added in v1.19.0
type TableValue struct {
Columns []string
Rows [][]string
// Detail is a line under the table.
Detail string
}
TableValue is what a "table" card shows: columns and rows of text the application formatted.
type TenantContext ¶
type TenantContext struct {
Enabled bool // Whether multi-tenant is enabled
TenantID string // Current tenant ID (empty = global/all tenants)
TenantField string // The column name for tenant isolation
AutoFilter bool // Whether Data Studio is confined to TenantID
Overridden bool // TenantID came from ?tenant= (superuser / tenant_switch)
}
TenantContext holds the tenant resolution of one admin request. It is built by tenantContextMiddleware from, in order of precedence, the ?tenant= override (gated and audited), the tenant the operator's account is bound to when the operator may not switch tenants (a request resolving another is refused), the tenant the host resolved for the request (PanelConfig.TenantResolver) and the configured default.
type Widget ¶ added in v1.10.0
type Widget struct {
// ID identifies the card. Lowercase letters, digits and dashes.
ID string
// Title is the label above the value.
Title string
// Description is the one line under it, for what a number cannot say.
Description string
// Permission is the RBAC action required on admin:dashboard (or, on a
// named dashboard, on admin:dashboard:<id>). Empty means "view": a
// widget is a reading of the application, and an operator who may not
// have that reading should not be shown it.
Permission string
// Link, when set, is where the card leads — a panel path
// ("/data-studio") or a page of the application's own.
Link string
// Load returns the value. It is called on every load of the screen,
// with a timeout: a widget is a glance, not a report.
Load func(ctx context.Context) (WidgetValue, error)
// Kind is what the card draws: "value" (the default, read from Load),
// "stat" (Stat), "line" or "bar" (Series), "table" (Table) or
// "records" (Records). An unknown kind, a kind without its function, or
// a function the kind would never call stops the application at
// startup, naming the widget.
Kind string
// Stat returns a headline figure and its change, for kind "stat".
Stat func(ctx context.Context) (StatValue, error)
// Series returns one or more series over the same labels, for kinds
// "line" and "bar".
Series func(ctx context.Context) (SeriesValue, error)
// Table returns columns and rows of text, for kind "table".
Table func(ctx context.Context) (TableValue, error)
// Records names the model a "records" card lists. It is the one kind
// with no function: the panel reads the rows itself, as the operator
// who is looking, through the same list the grid uses — so the card
// never shows a row that operator's tenant, row or field policies hide.
Records RecordList
// Span is how many columns of the grid the card takes, from 1 to the
// dashboard's Columns (4 on the overview). Zero is 1 for a value or a
// stat and 2 for a chart, a table or a list of records — never more
// than its screen has.
Span int
}
Widget is one card an application puts on the panel's overview, or on one of its dashboards.
type WidgetItem ¶ added in v1.10.0
WidgetItem is one row of a list widget.
type WidgetValue ¶ added in v1.10.0
type WidgetValue struct {
// Value is the headline: a count, an amount, a state. It is a string
// because the application knows how to format its own numbers, and a
// panel that formatted them would have to be told the currency, the
// locale and the precision to get it wrong in three ways.
Value string
// Detail is the smaller line under the value ("12% more than last
// week", "oldest: 3 days").
Detail string
// Items turn the card into a short list instead of a single number.
Items []WidgetItem
}
WidgetValue is what one widget shows.
Source Files
¶
- actions.go
- actions_custom.go
- actions_input.go
- actions_placement.go
- actions_result.go
- appearance.go
- audit.go
- audit_sql.go
- bootstrap_admin.go
- branding.go
- client_code.go
- dashboard.go
- dashboards.go
- datastudio.go
- default_auth.go
- exporters.go
- field_widgets.go
- fixtures.go
- flags.go
- handlers.go
- hardening.go
- i18n.go
- i18n_catalog.go
- importers.go
- inlines.go
- live.go
- live_cluster.go
- live_eventbus.go
- live_observ.go
- management.go
- management_migrations.go
- model_counts.go
- operators.go
- p2_features.go
- pages_custom.go
- panel.go
- permissions_field.go
- permissions_hints.go
- permissions_read.go
- permissions_row.go
- permissions_write.go
- precompressed.go
- prefix.go
- rbac.go
- record_validation.go
- relations.go
- runtime_cache.go
- runtime_email.go
- runtime_storage.go
- saved_views.go
- sessions.go
- storage_keys.go
- system.go
- tenant.go
- ui_fallback.go