shared

package
v0.1.35 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SkewNone    = 0 // below the warning threshold (or absent)
	SkewWarning = 1 // |skew| >= 10%
	SkewError   = 2 // |skew| >= 20%
)

Skew severity levels returned by SkewSeverity, used to pick a display style.

View Source
const (
	DefaultTableHeight  = 20
	DefaultSidebarWidth = 35
	DefaultFooterHeight = 3
	DefaultHeaderHeight = 3
	MinContentWidth     = 50
	MinContentHeight    = 10
)

Common constants

View Source
const (
	ErrorTypeDataLoad       = "data_load"
	ErrorTypeValidation     = "validation"
	ErrorTypeNavigation     = "navigation"
	ErrorTypeRender         = "render"
	ErrorTypeConfiguration  = "configuration"
	ErrorTypeConnection     = "connection"
	ErrorTypeAuthentication = "authentication"
	ErrorTypeTimeout        = "timeout"
)

Common error types

View Source
const ConfigValueMask = "**********"

ConfigValueMask is the placeholder shown in place of a sensitive config value.

Variables

View Source
var BrokerCSVHeader = []string{
	"ID", "Host", "Port", "Rack", "Disk Usage", "Leaders", "Replicas", "ISR", "Leader Skew", "Replica Skew",
}

BrokerCSVHeader is the column header row written by WriteBrokerCSV. It is shared so the in-app export and the `kafui get brokers --format csv` subcommand always agree on layout.

View Source
var ConsumerGroupCSVHeader = []string{
	"Group ID", "Members", "Topics", "Lag", "Coordinator", "State",
}

ConsumerGroupCSVHeader is the column header row written by WriteConsumerGroupCSV.

View Source
var Log *slog.Logger = slog.Default() // safe default until Init is called

Log is the application-wide structured logger. Available after InitLogger(). Other packages should use this directly:

shared.Log.Info("message", "key", value)
shared.Log.Error("something failed", "err", err)
View Source
var MessageCSVHeader = []string{"Partition", "Offset", "Timestamp", "Key", "Value", "Headers"}

MessageCSVHeader is the column header row.

View Source
var TopicCSVHeader = []string{
	"Name", "Partitions", "Replication Factor", "Message Count", "Out Of Sync", "Size", "Internal",
}

TopicCSVHeader is the column header row written by WriteTopicCSV.

Functions

func CreateHighlightedItem

func CreateHighlightedItem(item list.Item, searchQuery string) list.Item

CreateHighlightedItem creates a highlighted version of a list item

func DebugLog

func DebugLog(format string, args ...interface{})

DebugLog is a backward-compatible shim for code that uses the old API.

func DefaultExportPath

func DefaultExportPath(topic string, m api.Message) string

DefaultExportPath returns "./<topic>-<partition>-<offset>.json".

func ExportMessageJSON

func ExportMessageJSON(path string, topic string, m api.Message) error

ExportMessageJSON writes the message to path as pretty JSON containing key, value, offset, partition, headers (as an object/map name->value), and timestamp (RFC3339). Creates parent dirs as needed.

func FilterItems

func FilterItems(items []list.Item, query string, caseSensitive bool) []list.Item

FilterItems filters a slice of items based on a search query

func FormatBytes2dp

func FormatBytes2dp(n int64) string

FormatBytes2dp renders a byte count as a human-readable size with two decimal places using binary (1024) steps and SI-style unit labels (B, KB, MB, GB, …). Bytes below 1 KB are shown as a whole number, e.g. "512 B", larger values as "1.00 GB". Negative values are returned verbatim (as a signed byte count).

func FormatConfigValue

func FormatConfigValue(name, value string, sensitive bool) string

FormatConfigValue renders a broker config value for display:

  • sensitive entries are masked as ConfigValueMask;
  • keys ending ".bytes" with a positive integer value are shown as a human-readable size (non-positive / non-numeric values pass through as-is);
  • keys ending ".ms" get an " ms" suffix appended;
  • everything else is returned unchanged.

func FormatDiskUsage

func FormatDiskUsage(segmentSize int64, segmentCount int) string

FormatDiskUsage renders a broker's disk usage cell: "<size 2dp>, N segment(s)" or "N/A" when no log-dir data is available (segment count is zero).

func FormatISR

func FormatISR(inSync, replica int) (text string, alert bool)

FormatISR renders the in-sync-replica cell as "isr/replica". The cell is empty when the replica count is unavailable (<= 0). alert reports whether ISR is below the replica count (i.e. under-replicated) so the caller can style it.

func FormatSkew

func FormatSkew(skew *float64) string

FormatSkew renders a skew percentage as "%.2f%%" or "-" when absent (nil).

func FormatTimestamp

func FormatTimestamp(t time.Time) string

FormatTimestamp renders t in the configured display timezone.

func FuzzyFilterItems

func FuzzyFilterItems(items []list.Item, query string, caseSensitive bool) []list.Item

FuzzyFilterItems filters items using fuzzy matching

func FuzzyMatch

func FuzzyMatch(query, text string, caseSensitive bool) bool

FuzzyMatch performs fuzzy matching between a query and text

func HighlightSearchMatches

func HighlightSearchMatches(text, searchQuery string) string

HighlightSearchMatches highlights search query matches in text using lipgloss

func HighlightSearchMatchesWithConfig

func HighlightSearchMatchesWithConfig(text, searchQuery string, config HighlightConfig) string

HighlightSearchMatchesWithConfig highlights search matches with custom configuration

func InitLogger

func InitLogger()

InitLogger sets up the rotating file logger at ~/.kafui/kafui.log. It is idempotent and safe to call multiple times.

func IsValidDimensions

func IsValidDimensions(width, height int) bool

IsValidDimensions checks if the provided dimensions are valid for UI rendering

func NaturalLess

func NaturalLess(a, b string) bool

NaturalLess compares two strings naturally (numeric parts as numbers)

func RemoveHighlighting

func RemoveHighlighting(text string) string

RemoveHighlighting removes highlighting from text

func SavePrefs

func SavePrefs(p Prefs) error

SavePrefs writes prefs to the prefs file, creating the directory as needed.

func SetTimezone

func SetTimezone(name string) error

SetTimezone configures the display timezone from a config value: "local" (or ""), "UTC", or any IANA name (e.g. "Europe/Berlin"). An unknown name falls back to local time and returns an error so the caller can warn.

func SkewSeverity

func SkewSeverity(skew *float64) int

SkewSeverity classifies a skew value for styling: SkewError when |skew| >= 20%, SkewWarning when |skew| >= 10%, otherwise SkewNone. Absent (nil) is SkewNone.

func SortResourceListNaturally

func SortResourceListNaturally(items []list.Item)

SortResourceListNaturally sorts a slice of list items using natural sorting

func SortResourceListWithOptions

func SortResourceListWithOptions(items []list.Item, options SortOptions)

SortResourceListWithOptions sorts a slice of list items with the given options

func SortStringSlice

func SortStringSlice(items []string, options SortOptions)

SortStringSlice sorts a string slice with the given options

func SortTableRowsNaturally

func SortTableRowsNaturally(rows []table.Row)

SortTableRowsNaturally sorts a slice of table rows using natural sorting

func SortTableRowsWithOptions

func SortTableRowsWithOptions(rows []table.Row, options SortOptions)

SortTableRowsWithOptions sorts a slice of table rows with the given options

func WriteBrokerCSV

func WriteBrokerCSV(w io.Writer, brokers []api.BrokerInfo, stats map[int32]api.BrokerStats) error

WriteBrokerCSV writes brokers as CSV to w, enriched with stats when available. The ID column is annotated "(Active)" for the controller. Disk usage and skew columns reuse the shared list-cell formatters so UI and CSV output match. Rows are ordered by broker ID for deterministic output.

func WriteConsumerGroupCSV

func WriteConsumerGroupCSV(w io.Writer, groups []api.ConsumerGroup) error

WriteConsumerGroupCSV writes consumer groups as CSV to w. Undefined lag is written as an empty cell (never 0); unknown coordinator (<0) is empty too. Rows are ordered by group id for deterministic output.

func WriteMessagesCSV

func WriteMessagesCSV(w io.Writer, msgs []api.Message, f CSVFormat) error

WriteMessagesCSV writes msgs as CSV to w using the given format. Header row first, then one row per message. Headers column joins each "name=value" header with commas (a single field). Timestamp is RFC3339 (empty if zero).

func WriteTopicCSV

func WriteTopicCSV(w io.Writer, topics []TopicCSVRow) error

WriteTopicCSV writes topics as CSV to w. Rows are ordered by name for deterministic output. Unknown message counts/sizes (negative) render "N/A"; sizes are formatted human-readably via FormatBytes2dp.

Types

type CSVFormat

type CSVFormat struct {
	Separator      rune   // field separator, default ','
	Quote          rune   // quote char, default '"'
	QuoteAll       bool   // quote every field when true
	LineTerminator string // default "\n"
}

CSVFormat configures message CSV output.

func DefaultCSVFormat

func DefaultCSVFormat() CSVFormat

DefaultCSVFormat returns the default RFC-4180-ish format (comma, double-quote, \n).

type ConsumerGroupListItem

type ConsumerGroupListItem struct {
	GroupID     string
	Group       api.ConsumerGroup
	Selected    bool
	Highlighted bool
	SearchQuery string
}

ConsumerGroupListItem represents a consumer group item for list display

func (ConsumerGroupListItem) FilterValue

func (c ConsumerGroupListItem) FilterValue() string

func (ConsumerGroupListItem) GetID

func (c ConsumerGroupListItem) GetID() string

func (ConsumerGroupListItem) IsSelected

func (c ConsumerGroupListItem) IsSelected() bool

func (*ConsumerGroupListItem) SetSelected

func (c *ConsumerGroupListItem) SetSelected(selected bool)

type FilterableItem

type FilterableItem interface {
	FilterValue() string
}

FilterableItem represents an item that can be filtered

type HighlightConfig

type HighlightConfig struct {
	BackgroundColor string
	ForegroundColor string
	Bold            bool
	CaseSensitive   bool
	UseRegex        bool
}

HighlightConfig contains options for text highlighting

func DefaultHighlightConfig

func DefaultHighlightConfig() HighlightConfig

DefaultHighlightConfig returns default highlighting configuration

func SearchHighlightConfig

func SearchHighlightConfig() HighlightConfig

SearchHighlightConfig returns highlighting configuration for search matches Only changes font color, no background highlighting

type HighlightableItem

type HighlightableItem interface {
	GetDisplayText() string
	SetHighlight(query string)
	ClearHighlight()
}

HighlightableItem represents an item that can have highlighted content

type HighlightedResourceListItem

type HighlightedResourceListItem struct {
	ResourceItem ResourceItem
	SearchQuery  string
}

HighlightedResourceListItem wraps a resource item with search highlighting info

func (HighlightedResourceListItem) FilterValue

func (h HighlightedResourceListItem) FilterValue() string

func (HighlightedResourceListItem) GetID

type HighlightedTopicItem

type HighlightedTopicItem struct {
	Name        string
	Topic       api.Topic
	SearchQuery string
}

HighlightedTopicItem wraps a topic item with search highlighting info

func (HighlightedTopicItem) FilterValue

func (h HighlightedTopicItem) FilterValue() string

func (HighlightedTopicItem) GetID

func (h HighlightedTopicItem) GetID() string

type MessageListItem

type MessageListItem struct {
	Message     api.Message
	Index       int
	Selected    bool
	Highlighted bool
	SearchQuery string
}

MessageListItem represents a message item for display

func (MessageListItem) FilterValue

func (m MessageListItem) FilterValue() string

func (MessageListItem) GetID

func (m MessageListItem) GetID() string

func (MessageListItem) IsSelected

func (m MessageListItem) IsSelected() bool

func (*MessageListItem) SetSelected

func (m *MessageListItem) SetSelected(selected bool)

type MinimalResourceItem

type MinimalResourceItem struct {
	ID string
}

MinimalResourceItem is a minimal implementation of ResourceItem for fallback cases

func (*MinimalResourceItem) GetDetails

func (m *MinimalResourceItem) GetDetails() map[string]string

func (*MinimalResourceItem) GetID

func (m *MinimalResourceItem) GetID() string

func (*MinimalResourceItem) GetValues

func (m *MinimalResourceItem) GetValues() []string

type NaturalSort

type NaturalSort []string

NaturalSort sorts strings in natural order (numbers in logical order)

func (NaturalSort) Len

func (s NaturalSort) Len() int

func (NaturalSort) Less

func (s NaturalSort) Less(i, j int) bool

func (NaturalSort) Swap

func (s NaturalSort) Swap(i, j int)
type Navigation struct {
	Current   string
	Previous  []string
	CanGoBack bool
}

Navigation represents navigation state and history

type PageState

type PageState struct {
	Loading    bool
	Error      error
	FilterMode bool
	SearchMode bool
	EditMode   bool
}

PageState represents the current state of a page

type Prefs

type Prefs struct {
	HideInternalTopics bool `json:"hideInternalTopics"`
	// SavedFilters are named smart-filter expressions (MSG-25).
	SavedFilters []SavedFilter `json:"savedFilters,omitempty"`
	// Projections maps a topic name to its column projections (MSG-26).
	Projections map[string]TopicProjection `json:"projections,omitempty"`
}

Prefs holds small, user-local UI preferences persisted across runs. Add fields as new persisted toggles are introduced.

func LoadPrefs

func LoadPrefs() Prefs

LoadPrefs reads the prefs file. A missing/unreadable file yields zero-value Prefs (never an error) so callers can use it unconditionally on startup.

type ResourceItem

type ResourceItem interface {
	GetID() string
	GetValues() []string
	GetDetails() map[string]string
}

ResourceItem represents a displayable resource item

type ResourceListItem

type ResourceListItem struct {
	ResourceItem ResourceItem
	Selected     bool
	Highlighted  bool
	SearchQuery  string
}

ResourceListItem wraps a resource item for list display

func (ResourceListItem) FilterValue

func (r ResourceListItem) FilterValue() string

func (ResourceListItem) GetID

func (r ResourceListItem) GetID() string

func (ResourceListItem) IsSelected

func (r ResourceListItem) IsSelected() bool

func (*ResourceListItem) SetSelected

func (r *ResourceListItem) SetSelected(selected bool)

type SavedFilter

type SavedFilter struct {
	Name string `json:"name"`
	Expr string `json:"expr"`
}

SavedFilter is a named smart-filter expression persisted across runs (MSG-25).

type SearchConfig

type SearchConfig struct {
	CaseSensitive    bool
	UseRegex         bool
	UseFuzzy         bool
	HighlightMatches bool
}

SearchConfig represents search configuration

type SelectableItem

type SelectableItem interface {
	GetID() string
	IsSelected() bool
	SetSelected(selected bool)
}

SelectableItem represents an item that can be selected

type SlogWriter

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

SlogWriter is an io.Writer that routes each written line into a *slog.Logger at INFO level. Use it to redirect legacy log.Logger or fmt.Fprintf calls (e.g. sarama.Logger, errWriter) into the structured log file without touching the terminal.

func NewSlogWriter

func NewSlogWriter(logger *slog.Logger) *SlogWriter

NewSlogWriter creates a new SlogWriter backed by the given logger.

func (*SlogWriter) Write

func (w *SlogWriter) Write(p []byte) (int, error)

Write buffers bytes and emits a log line for each newline-terminated record.

type SortOptions

type SortOptions struct {
	Order         SortOrder
	CaseSensitive bool
	Natural       bool
	ColumnIndex   int
}

SortOptions contains options for sorting operations

func DefaultSortOptions

func DefaultSortOptions() SortOptions

DefaultSortOptions returns default sorting options

type SortOrder

type SortOrder int

SortOrder represents different sorting orders

const (
	SortAscending SortOrder = iota
	SortDescending
)

type StatusInfo

type StatusInfo struct {
	Message    string
	Type       StatusType
	Timestamp  string
	Persistent bool
}

StatusInfo represents status information for display

type StatusType

type StatusType int

StatusType represents different types of status messages

const (
	StatusTypeInfo StatusType = iota
	StatusTypeSuccess
	StatusTypeWarning
	StatusTypeError
)

type TableConfig

type TableConfig struct {
	Columns    []table.Column
	Styles     table.Styles
	Width      int
	Height     int
	ShowHeader bool
	Selectable bool
}

TableConfig represents table configuration

type TopicCSVRow

type TopicCSVRow struct {
	Name              string
	Partitions        int32
	ReplicationFactor int16
	MessageCount      int64
	OutOfSync         int
	Size              int64
	Internal          bool
}

TopicCSVRow is one topic's exported row. MessageCount/Size are negative when unknown (rendered "N/A").

type TopicListItem

type TopicListItem struct {
	Name        string
	Topic       api.Topic
	Selected    bool
	Highlighted bool
	SearchQuery string
}

TopicListItem represents a topic item for list display

func (TopicListItem) FilterValue

func (t TopicListItem) FilterValue() string

func (TopicListItem) GetID

func (t TopicListItem) GetID() string

func (TopicListItem) IsSelected

func (t TopicListItem) IsSelected() bool

func (*TopicListItem) SetSelected

func (t *TopicListItem) SetSelected(selected bool)

type TopicProjection

type TopicProjection struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

TopicProjection holds the key/value JSON-path projections for a topic's message table columns (MSG-26). Empty path means "no projection".

type UIError

type UIError struct {
	Type    string
	Message string
	Cause   error
}

Common error types

func NewUIError

func NewUIError(errorType, message string, cause error) UIError

func (UIError) Error

func (e UIError) Error() string

type ViewDimensions

type ViewDimensions struct {
	Width         int
	Height        int
	ContentWidth  int
	ContentHeight int
	SidebarWidth  int
	FooterHeight  int
	HeaderHeight  int
}

ViewDimensions represents view dimensions and layout information

func CalculateContentDimensions

func CalculateContentDimensions(totalWidth, totalHeight, sidebarWidth, footerHeight, headerHeight int) ViewDimensions

Helper functions for common operations

Directories

Path Synopsis
Package aclcsv provides pure CSV serialization/parsing of ACL bindings and a declarative sync (diff + apply) between a desired binding set and the cluster.
Package aclcsv provides pure CSV serialization/parsing of ACL bindings and a declarative sync (diff + apply) between a desired binding set and the cluster.

Jump to

Keyboard shortcuts

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