admin

package
v0.1.0-alpha.14 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 19 Imported by: ? 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 admin provides database monitoring and operator HTTP endpoints.

It is deliberately separate from the database package: creating a DB never starts a sampler, a goroutine, or a network listener.

Index

Constants

View Source
const PrometheusContentType = "text/plain; version=0.0.4; charset=utf-8"

PrometheusContentType identifies the supported Prometheus text response format.

Variables

View Source
var (
	// ErrRuntimeCaptureBusy reports that another admin runtime capture is active.
	ErrRuntimeCaptureBusy = errors.New("meldbase admin: another runtime capture is active")
	// ErrRuntimeCaptureLimit reports that capture output exceeded its byte limit.
	ErrRuntimeCaptureLimit = errors.New("meldbase admin: runtime capture byte limit reached")
)
View Source
var (
	// ErrClosed reports an attempt to subscribe to a closed sampler.
	ErrClosed = errors.New("meldbase admin: sampler closed")
	// ErrSubscriberLimit reports that the sampler has reached its subscriber limit.
	ErrSubscriberLimit = errors.New("meldbase admin: subscriber limit reached")
)

Functions

func MarshalPrometheus

func MarshalPrometheus(sample Sample) []byte

MarshalPrometheus converts a database sample into Prometheus text metrics.

It uses text exposition format 0.0.4 and emits only fixed metric names and fixed-enum labels; no application-controlled string can enter the output.

Types

type Authorizer

type Authorizer func(*http.Request) bool

Authorizer decides whether a request may access the operator API.

func NewBearerTokenAuthorizer

func NewBearerTokenAuthorizer(token string) (Authorizer, error)

NewBearerTokenAuthorizer creates an operator access check using constant-time bearer token comparisons.

Tokens are intentionally not accepted in URLs, where they leak into logs and browser history.

type DiagnosticSource

type DiagnosticSource interface {
	DiagnosticSnapshotAfter(after uint64, limit int) meldbase.DiagnosticSnapshot
}

DiagnosticSource supplies bounded diagnostic snapshots after an event sequence.

type Handler

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

Handler serves operator statistics and optional dashboard, metrics, and diagnostic endpoints.

func NewHandler

func NewHandler(options HandlerOptions) (*Handler, error)

NewHandler validates operator settings and registers the enabled HTTP routes.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP routes operator requests through origin checks, authorization, and auditing.

Dashboard pages and assets are public after the origin check; API requests require operator authorization. Preflight requests use their own validation.

type HandlerOptions

type HandlerOptions struct {
	Sampler        *Sampler
	Authorize      Authorizer
	AllowedOrigins []string
	WriteTimeout   time.Duration
	ServeDashboard bool
	ServeMetrics   bool
	Diagnostics    DiagnosticSource
	IndexCatalog   IndexCatalogSource
	AuditWriter    io.Writer
}

HandlerOptions configures operator access, sampled data, and optional dashboard and diagnostic routes.

type HealthLevel

type HealthLevel string

HealthLevel identifies an aggregate health assessment or unavailable evidence.

const (
	// HealthUnavailable marks a component without enough evidence for an assessment.
	HealthUnavailable HealthLevel = "unavailable"
	// HealthHealthy marks a component with no detected health signals.
	HealthHealthy HealthLevel = "healthy"
	// HealthDegraded marks a component with detected pressure or recoverable failures.
	HealthDegraded HealthLevel = "degraded"
	// HealthCritical marks a component with severe pressure or disabled availability.
	HealthCritical HealthLevel = "critical"
)

func (HealthLevel) Severity

func (level HealthLevel) Severity() (uint64, bool)

Severity returns a numeric health level when an assessment is available.

Healthy maps to 0, degraded to 1, and critical to 2. Exporters omit unavailable assessments.

type HealthSignals

type HealthSignals struct {
	DatabaseClosed               bool `json:"databaseClosed"`
	WritesDisabled               bool `json:"writesDisabled"`
	ReactiveQueuePressure        bool `json:"reactiveQueuePressure"`
	ReactiveQueueOverflow        bool `json:"reactiveQueueOverflow"`
	SlowConsumer                 bool `json:"slowConsumer"`
	PersistentFreeSpaceDiscarded bool `json:"persistentFreeSpaceDiscarded"`
	CommitRetentionPressure      bool `json:"commitRetentionPressure"`
	IndexBuildFailed             bool `json:"indexBuildFailed"`
	IndexBuildRetentionPressure  bool `json:"indexBuildRetentionPressure"`
	StorageQuotaExhausted        bool `json:"storageQuotaExhausted"`
	StorageLimitRejected         bool `json:"storageLimitRejected"`
	CommitCoordinatorPressure    bool `json:"commitCoordinatorPressure"`
	CommitCoordinatorRejected    bool `json:"commitCoordinatorRejected"`
	PrimaryWriteFenceRejected    bool `json:"primaryWriteFenceRejected"`
	DurabilityFailure            bool `json:"durabilityFailure"`
	RollbackAnchorDegraded       bool `json:"rollbackAnchorDegraded"`
	TelemetryDeliveryDropped     bool `json:"telemetryDeliveryDropped"`
	TransportBusy                bool `json:"transportBusy"`
	RPCOutcomeUnknown            bool `json:"rpcOutcomeUnknown"`
	WorkerProtocolFailure        bool `json:"workerProtocolFailure"`
}

HealthSignals identifies the conditions behind the current health assessment.

Event signals describe increases during the latest sample window; state signals remain set while the underlying condition remains true.

type HealthStatus

type HealthStatus struct {
	Overall    HealthLevel   `json:"overall"`
	Database   HealthLevel   `json:"database"`
	Durability HealthLevel   `json:"durability"`
	Storage    HealthLevel   `json:"storage"`
	Realtime   HealthLevel   `json:"realtime"`
	Telemetry  HealthLevel   `json:"telemetry"`
	Transport  HealthLevel   `json:"transport"`
	Signals    HealthSignals `json:"signals"`
}

HealthStatus groups component assessments and the signals explaining them.

type IndexCatalogSource

type IndexCatalogSource interface {
	IndexCatalog(context.Context) ([]meldbase.IndexCatalogEntry, error)
}

IndexCatalogSource supplies published index definitions for the operator API.

Its output is exposed only after operator authentication.

type Rates

type Rates struct {
	Valid                      bool    `json:"valid"`
	WindowSeconds              float64 `json:"windowSeconds"`
	CommitsPerSecond           float64 `json:"commitsPerSecond"`
	ChangesPerSecond           float64 `json:"changesPerSecond"`
	QueriesPerSecond           float64 `json:"queriesPerSecond"`
	FailedQueriesPerSecond     float64 `json:"failedQueriesPerSecond"`
	DocumentsExaminedPerSecond float64 `json:"documentsExaminedPerSecond"`
	DocumentsReturnedPerSecond float64 `json:"documentsReturnedPerSecond"`
	KeysExaminedPerSecond      float64 `json:"keysExaminedPerSecond"`
	PredicateStepsPerSecond    float64 `json:"predicateStepsPerSecond"`
	PublishedChangesPerSecond  float64 `json:"publishedChangesPerSecond"`
	DeltaDeliveriesPerSecond   float64 `json:"deltaDeliveriesPerSecond"`
	WALBytesPerSecond          float64 `json:"walBytesPerSecond"`
	PageCacheHitRatio          float64 `json:"pageCacheHitRatio"`
	DocumentCacheHitRatio      float64 `json:"documentCacheHitRatio"`
	RPCRequestsPerSecond       float64 `json:"rpcRequestsPerSecond"`
	RPCFailuresPerSecond       float64 `json:"rpcFailuresPerSecond"`
	RPCBusyPerSecond           float64 `json:"rpcBusyPerSecond"`
	RPCRatesValid              bool    `json:"rpcRatesValid"`
}

Rates reports activity rates between adjacent samples and cumulative cache hit ratios.

Valid is false for the first sample and after a database reopen or counter reset. Ratios are cumulative for the current process session.

type RuntimeCaptureKind

type RuntimeCaptureKind string

RuntimeCaptureKind selects a CPU profile, heap snapshot, or runtime trace.

const (
	// RuntimeCPUProfile selects a timed CPU profile.
	RuntimeCPUProfile RuntimeCaptureKind = "cpu"
	// RuntimeHeapProfile selects an immediate heap snapshot.
	RuntimeHeapProfile RuntimeCaptureKind = "heap"
	// RuntimeTrace selects a timed Go runtime trace.
	RuntimeTrace RuntimeCaptureKind = "trace"
)

type RuntimeCaptureOptions

type RuntimeCaptureOptions struct {
	// Duration applies to CPU profiles and runtime traces. Zero selects ten
	// seconds. Heap snapshots are immediate and require zero.
	Duration time.Duration
}

RuntimeCaptureOptions selects the duration of one timed capture.

type RuntimeCaptureResult

type RuntimeCaptureResult struct {
	Kind      RuntimeCaptureKind
	StartedAt time.Time
	Duration  time.Duration
	Bytes     int64
	Truncated bool
}

RuntimeCaptureResult reports capture timing, output size, and whether output was truncated.

type RuntimeProfiler

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

RuntimeProfiler captures CPU profiles, heap snapshots, and runtime traces within configured limits.

It does not start a listener or retain capture bytes. The caller owns authorization, the output writer, and its lifetime. CPU profiles and runtime traces add process-wide overhead; use them for short diagnostic windows.

func NewRuntimeProfiler

func NewRuntimeProfiler(options RuntimeProfilerOptions) (*RuntimeProfiler, error)

NewRuntimeProfiler creates a profiler after validating duration and output limits.

func (*RuntimeProfiler) Capture

func (profiler *RuntimeProfiler) Capture(ctx context.Context, writer io.Writer, kind RuntimeCaptureKind, options RuntimeCaptureOptions) (result RuntimeCaptureResult, resultErr error)

Capture writes a bounded runtime profile or trace and records its outcome.

func (*RuntimeProfiler) Stats

func (profiler *RuntimeProfiler) Stats() RuntimeProfilerStats

Stats returns the profiler's aggregate capture counters.

type RuntimeProfilerOptions

type RuntimeProfilerOptions struct {
	MaxDuration time.Duration
	MaxBytes    int64
}

RuntimeProfilerOptions sets duration and output limits for runtime captures.

type RuntimeProfilerStats

type RuntimeProfilerStats struct {
	Active    uint64
	Attempts  uint64
	Completed uint64
	Failed    uint64
	Bytes     uint64
}

RuntimeProfilerStats reports capture activity, outcomes, and total output bytes.

type Sample

type Sample struct {
	Sequence uint64                  `json:"sequence"`
	Stats    meldbase.DBStats        `json:"stats"`
	Rates    Rates                   `json:"rates"`
	Sampler  SamplerStatus           `json:"sampler"`
	Health   HealthStatus            `json:"health"`
	Server   *meldserver.ServerStats `json:"server,omitempty"`
}

Sample groups database statistics, activity rates, and health at one sampling point.

type Sampler

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

Sampler periodically collects database statistics and keeps a fixed-size history.

Each subscriber has a single replaceable slot, so a slow consumer can never block sampling or database work.

func NewSampler

func NewSampler(source StatsSource, options SamplerOptions) (*Sampler, error)

NewSampler validates settings, captures an initial sample, and starts periodic sampling.

func (*Sampler) Close

func (s *Sampler) Close() error

Close closes subscriber streams and waits for periodic sampling to stop.

func (*Sampler) History

func (s *Sampler) History() []Sample

History returns a copy of the retained samples in oldest-first order.

func (*Sampler) Latest

func (s *Sampler) Latest() (Sample, bool)

Latest returns the most recent sample and whether a sample is available.

func (*Sampler) Status

func (s *Sampler) Status() SamplerStatus

Status returns the sampler's current counters and retained history size.

func (*Sampler) Subscribe

func (s *Sampler) Subscribe(ctx context.Context) (*Subscription, error)

Subscribe creates a bounded latest-sample stream that closes when its context ends.

type SamplerOptions

type SamplerOptions struct {
	Interval       time.Duration
	HistorySize    int
	MaxSubscribers int
	Server         ServerStatsSource
}

SamplerOptions sets the sampling interval, history size, subscriber limit, and optional server source.

type SamplerStatus

type SamplerStatus struct {
	Samples           uint64 `json:"samples"`
	Subscribers       uint64 `json:"subscribers"`
	DroppedDeliveries uint64 `json:"droppedDeliveries"`
	HistorySamples    uint64 `json:"historySamples"`
}

SamplerStatus reports sample counts, retained history, subscribers, and replaced deliveries.

type ServerStatsSource

type ServerStatsSource interface {
	Stats() meldserver.ServerStats
}

ServerStatsSource supplies server activity snapshots to the sampler.

type StatsSource

type StatsSource interface {
	Stats() meldbase.DBStats
}

StatsSource supplies database activity snapshots to the sampler.

*meldbase.DB implements this interface.

type Subscription

type Subscription struct {
	C <-chan Sample
	// contains filtered or unexported fields
}

Subscription exposes a sample stream that can be closed independently.

func (*Subscription) Close

func (s *Subscription) Close()

Close removes this subscription and closes its sample stream.

Jump to

Keyboard shortcuts

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