monitor

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 32 Imported by: 0

README

Monitor SDK

Monitor is a lightweight Go metrics SDK with Prometheus Remote Write and an optional Prometheus HTTP pull exporter. It provides counters, labeled counters/gauges, official Prometheus histograms, system metrics, bounded snapshot construction, and DNS-aware Remote Write delivery.

Installation

go get github.com/nikiz24/monitor

Push-only quick start

The pull exporter is disabled by default. Existing push-only configurations remain valid and do not start an HTTP listener or allocate a snapshot cache.

package main

import (
    "log"
    "time"

    "github.com/nikiz24/monitor"
)

func main() {
    cfg := monitor.Config{
        Namespace:           "myapp",
        Subsystem:           "prod",
        ServiceName:         "api",
        RemoteWriteURL:      "http://prometheus:9090/api/v1/write",
        RemoteWriteInterval: 15 * time.Second,
    }
    if err := monitor.Init(cfg); err != nil {
        log.Fatal(err)
    }
    defer monitor.Shutdown()

    monitor.IncrementCounter("requests_total")
    monitor.SetLabeledCounter("connections", 42, "type", "websocket")
    monitor.ObserveHistogram("response_time_seconds", 0.123)
}

Prometheus pull exporter

Set PrometheusExporter to enable pull. The following configuration enables both Remote Write and /metrics:

cfg := monitor.Config{
    Namespace: "myapp", Subsystem: "prod", ServiceName: "api",
    RemoteWriteURL: "http://prometheus:9090/api/v1/write",
    RemoteWriteInterval: 15*time.Second,
    PrometheusExporter: &monitor.PrometheusExporterConfig{ListenAddress: ":9091", Path: "/metrics"},
}

Use this Prometheus scrape configuration:

scrape_configs:
  - job_name: monitor-sdk
    scrape_interval: 15s
    honor_labels: true
    static_configs:
      - targets:
          - myapp:9091

Warning: push and pull may be enabled together, but they must never feed the same logical backend. The SDK does not deduplicate the two delivery paths and cannot make them transactional; sending both to one backend produces duplicate or inconsistent samples.

For pull-only operation, leave RemoteWriteURL empty. Leaving PrometheusExporter nil preserves push-only behavior.

Effective defaults

Zero values below select these defaults after the exporter is enabled. ListenAddress is the exception: it is required and has no default.

Setting Effective default Contract
ListenAddress required Non-empty net.Listen TCP address
Path /metrics Absolute, clean, canonical literal ASCII path
SnapshotCacheTTL 1s Shared push/pull snapshot lifetime
MaxConcurrentScrapes 4 Accepted HTTP responses in flight
MaxStoredSeries 1,000,000 Active-store emergency ceiling
MaxEstimatedStoreBytes 256 MiB Estimated active-series storage ceiling
MaxSnapshotBytes 128 MiB Canonical, encoded payload, and construction guard
MaxLabelsPerSeries 32 Common plus business labels
MaxLabelBytesPerSeries 16 KiB Label-name and value bytes per series
RemoteWriteBatchSeries 10,000 Maximum series materialized per Remote Write batch
ReadHeaderTimeout 5s HTTP request-header timeout
WriteTimeout 10s HTTP response timeout
IdleTimeout 60s HTTP keep-alive idle timeout
ShutdownTimeout 10s Graceful exporter shutdown deadline

The default 1-second cache is appropriate for 15-, 30-, and 60-second scrape intervals. For a scrape interval below 10 seconds, set SnapshotCacheTTL <= scrape_interval / 10. Increasing the TTL reduces rebuilds but deliberately serves older values; it is a freshness tradeoff, not free capacity.

MaxStoredSeries=1,000,000 is an emergency ceiling for the active metric store. It is not the 1-second snapshot cache. Byte and per-series label limits usually reject new cardinality first. Admission may clean expired series when approaching a limit, but the global guard does not evict unexpired old series. The standard labeled collector TTL remains 60 minutes unless explicitly changed.

HTTP behavior and failure responses

The endpoint supports GET and HEAD; GET negotiates gzip from Accept-Encoding, and HEAD returns the same representation headers without a body. Other methods return 405. The exporter owns a dedicated http.Server and http.ServeMux; it never registers with http.DefaultServeMux.

The listener provides no TLS and no authentication. Bind it to a protected interface or place an authenticated TLS reverse proxy in front of it. The path must be an absolute, clean, canonical literal ASCII path; escaped or alternate spellings are rejected so the dedicated mux has one route identity.

  • 503 means scrape concurrency exhaustion, a snapshot/resource byte limit, or a busy retired-payload generation.
  • 500 means validation, collector, or output-build failure before a response is committed.
  • A response write failure after headers are committed is reported through observability and ErrorHandler; it cannot change the already committed 200.
  • A failed refresh never serves an expired or stale snapshot as fallback.
Labels and collisions

The SDK's raw common labels are _instance_, instance, _target_, and every entry in Config.CustomLabels. Business labels supplied to a metric are merged with those labels consistently in push and pull. __name__ is special to Remote Write and is not emitted as an ordinary label in text exposition.

Keep honor_labels: true in Prometheus. With honor_labels: false, Prometheus renames the SDK's instance label to exported_instance when it supplies its own target label, so pull labels no longer match Remote Write labels.

The system-reserved labels are __name__, _instance_, instance, _target_, le, and quantile. When PrometheusExporter is enabled, CustomLabels additionally cannot use the fixed self-metric dimensions result, kind, consumer, code, or reason. Those names remain valid business labels on other metric families. Duplicate labels and conflicts between custom and business labels are rejected.

When PrometheusExporter is enabled, the following 11 self-metric families are SDK-owned and cannot be registered by business collectors:

monitor_snapshot_builds_total
monitor_snapshot_build_duration_seconds
monitor_snapshot_series
monitor_snapshot_bytes
monitor_snapshot_cache_requests_total
monitor_exporter_requests_total
monitor_exporter_requests_in_flight
monitor_metric_errors_total
monitor_dropped_series_total
monitor_remote_write_batches_total
monitor_remote_write_batch_series

Push-only managers preserve the legacy Remote Write profile: they do not emit SDK self metrics, so the raw family and dimension names above remain available to business collectors and CustomLabels in that mode.

Checked APIs such as TryAddCounter, TryIncrementLabeledCounter, TrySetLabeledCounter, and RegisterCollector return validation or ownership errors synchronously. Legacy void update APIs preserve their signatures: they drop an invalid operation and record a fixed-cardinality monitor_metric_errors_total{reason=...} sample plus a rate-limited log rather than creating a dynamic error series.

Collectors and histograms

The legacy Collector interface remains supported:

type MyCollector struct {
    monitor.BaseCollector
}

func (c *MyCollector) Collect() []monitor.Metric {
    return []monitor.Metric{{
        Name: "queue_depth", Value: 3, MetricType: monitor.Gauge,
        Labels: map[string]string{"queue": "default"},
        Timestamp: time.Now(),
    }}
}

Register global collectors with monitor.RegisterCollector, which returns any checked registration error. A custom manager also exposes CheckedCollectorRegistrar.RegisterCollectorChecked without changing the legacy Manager interface.

SnapshotCollector is the allocation-efficient fast path. Its CollectTo method receives a synchronous SnapshotAppender; the collector must not retain the appender, use it concurrently, mutate submitted histogram DTOs, or claim unvalidated capacity. This is a trust boundary for custom code. The SDK bounds its own snapshot and payload allocations, but it cannot bound arbitrary memory allocated inside a legacy Collector.Collect() before that method returns.

Histograms use the official prometheus.Histogram implementation internally. They are intentionally unregistered and never touch prometheus.DefaultRegistry or prometheus.DefaultGatherer.

monitor.RegisterHistogramBuckets("response_time_seconds", []float64{0.01, 0.1, 1, 5})
monitor.ObserveHistogram("response_time_seconds", 0.125)

Cardinality and 100K operation

Labeled collectors support explicit TTL and local max-series controls:

collector := monitor.NewApplicationCollector("http_requests", logger)
collector.SetTTL(30 * time.Minute)
collector.SetMaxSeries(50_000)
collector.Inc("total", "method", "GET", "route", "/v1/users")

The exporter is designed to build and expose 100,000 ordinary labeled series when their actual label mix fits the configured store, per-series, and snapshot budgets. The 1,000,000-series default is not a promise that every label shape fits in 256 MiB or that a snapshot fits in 128 MiB. Benchmark representative labels, avoid unbounded IDs, and monitor the SDK self metrics.

Remote Write expands at most RemoteWriteBatchSeries (10,000 by default) at a time, so a 100K snapshot does not become one 100K protocol object graph. Batches are sent sequentially. Delivery is best effort and may be partial: accepted batches cannot be rolled back if a later batch fails, and the next interval attempts a fresh complete snapshot. There is no WAL or unbounded retry queue. ForceWrite uses the same non-blocking single-flight gate as the periodic writer. If a write is already active, another call returns ErrRemoteWriteBusy immediately, before snapshot cache lookup, snapshot build, or network request work begins.

Status, health, and error callbacks

monitor.HealthCheck() reports an enabled exporter that has not started, lost its listener, or failed at runtime. A disabled exporter does not make an otherwise initialized manager unhealthy.

monitor.GetStatus() includes the existing initialization fields and these exporter fields:

exporter_enabled
exporter_listening
exporter_address
exporter_path
snapshot_cached
snapshot_age
stored_series
estimated_store_bytes
last_exporter_error
last_exporter_error_time

Config.ErrorHandler receives exporter lifecycle, snapshot-build, and response output failures. Dispatch is asynchronous from the failing operation, serialized to one callback at a time, bounded in retained error state, and panic-safe. The callback must return promptly: an indefinitely blocked callback delays all later error notifications. Hot-path metric validation uses the fixed self metric and logging path rather than invoking this callback.

Basic metric APIs

monitor.IncrementCounter("requests_total")
monitor.AddCounter("bytes_processed_total", 1024)
monitor.SetCounter("active_connections", 42)

monitor.IncrementLabeledCounter("http_requests_total",
    "method", "GET", "status", "200")
monitor.SetLabeledCounter("connected_users", 5,
    "region", "us-west", "type", "premium")
monitor.DeleteLabeledCounter("connected_users",
    "region", "us-west", "type", "premium")

Prometheus sample values are float64. Integer and internal counters remain monotonic according to their APIs, but after 2^53 the exported Prometheus value cannot represent every one-unit increment. Do not rely on unit precision past that point or interpret the implementation's integer storage as a promise that a counter can never wrap.

System metrics and DNS

if err := monitor.RegisterSystemMetricsCollector(logger); err != nil {
    log.Fatal(err)
}

alloc, sys, heapInUse := monitor.GetProcessMemory()
_ = alloc
_ = sys
_ = heapInUse

Advanced Remote Write DNS resolution remains optional:

cfg := monitor.Config{
    Namespace: "myapp", Subsystem: "prod", ServiceName: "api",
    RemoteWriteURL: "http://prometheus:9090/api/v1/write",
    RemoteWriteInterval: 15 * time.Second,
    DNSEnable: true,
    DNSCacheTTL: 10 * time.Minute,
    DNSRefreshInterval: 5 * time.Minute,
    DNSTimeout: 800 * time.Millisecond,
    DNSUDPServers: []string{"1.1.1.1:53", "8.8.8.8:53"},
    DNSTLSServers: []string{"1.1.1.1:853"},
    DNSDoHEndpoints: []string{"https://cloudflare-dns.com/dns-query"},
}

Always call monitor.Shutdown() so the exporter, cache, Remote Write, and DNS workers release their resources.

Verification

Run the complete functional suite with strict pointer checking through the formal target:

make test-checkptr

The target executes this exact command:

go test -tags=checkptr_full -gcflags=all=-d=checkptr=2 ./... -count=1

The checkptr_full tag disables only numeric testing.AllocsPerRun assertions, because checkptr intentionally adds per-operation allocations. Each measured operation still runs once, and all functional, protocol, GC, finalizer, memory-budget, and ownership tests remain enabled.

License

MIT License. See LICENSE.

Documentation

Overview

Package monitor provides a lightweight metrics collection SDK for Go applications with Prometheus Remote Write and an optional HTTP pull exporter.

Design goals:

  • Minimal overhead and allocations for hot paths
  • Thread-safe primitives built with atomic operations
  • Bounded memory with TTL and max-series limits for labeled counters
  • Consistent Prometheus labels across push and pull

Push-only usage remains the default:

config := monitor.Config{
  Namespace:           "myapp",
  Subsystem:           "prod",
  ServiceName:         "service",
  RemoteWriteURL:      "http://prometheus:9090/api/v1/write",
  RemoteWriteInterval: 15 * time.Second,
}

if err := monitor.Init(config); err != nil {
  log.Fatal(err)
}
defer monitor.Shutdown()

monitor.IncrementCounter("requests_total")
monitor.SetLabeledCounter("connections", 42, "type", "websocket")
monitor.ObserveHistogram("response_time", 0.123)

To enable the pull exporter, set PrometheusExporter explicitly:

cfg := monitor.Config{
  Namespace: "myapp", Subsystem: "prod", ServiceName: "api",
  RemoteWriteURL: "http://prometheus:9090/api/v1/write",
  RemoteWriteInterval: 15 * time.Second,
  PrometheusExporter: &monitor.PrometheusExporterConfig{
    ListenAddress: ":9091",
    Path:          "/metrics",
  },
}

Push and pull may run together, but must not deliver to the same logical backend: the SDK does not deduplicate or transactionally coordinate them.

Index

Constants

View Source
const RegistrySnapshotSchemaVersionV1 = "v1"

RegistrySnapshotSchemaVersionV1 identifies the initial structured registry snapshot contract.

Variables

View Source
var (
	// ErrAggregationInvalidConfig identifies an invalid AggregationConfig value.
	ErrAggregationInvalidConfig = errors.New("invalid aggregation config")
	// ErrAggregationInvalidLimits identifies an invalid AggregationLimits value.
	ErrAggregationInvalidLimits = errors.New("invalid aggregation limits")
	// ErrAggregationLimit identifies a generation rejected by an aggregation limit.
	ErrAggregationLimit = errors.New("aggregation limit exceeded")
	// ErrAggregationSourceResult identifies an invalid result passed to the merger.
	ErrAggregationSourceResult = errors.New("invalid aggregation source result")
	// ErrAggregationProviderContract identifies provider callback lifecycle misuse.
	ErrAggregationProviderContract = errors.New("aggregation provider contract violation")
)
View Source
var (
	ErrSeriesLimit              = errors.New("monitor series limit reached")
	ErrCollectorLimiterConflict = errors.New("monitor collector already attached to a different series limiter")
	ErrManagerStopped           = errors.New("monitor manager stopped")
)
View Source
var (
	// ErrRegistrySnapshotMalformed identifies invalid or truncated snapshot wire data.
	ErrRegistrySnapshotMalformed = errors.New("malformed registry snapshot")
	// ErrRegistrySnapshotUnknownVersion identifies an unsupported schema or wire version.
	ErrRegistrySnapshotUnknownVersion = errors.New("unknown registry snapshot version")
	// ErrRegistrySnapshotLimit identifies a configured decode limit violation.
	ErrRegistrySnapshotLimit = errors.New("registry snapshot decode limit exceeded")
	// ErrRegistrySnapshotInvalidLimits identifies an invalid DecodeLimits configuration.
	ErrRegistrySnapshotInvalidLimits = errors.New("invalid registry snapshot decode limits")
)
View Source
var (
	ErrDuplicateSeries    = errors.New("duplicate metric series")
	ErrMetricTypeConflict = errors.New("metric family type conflict")
	ErrUnsupportedSummary = errors.New("summary requires structured collector")
	ErrMalformedHistogram = errors.New("malformed legacy histogram")
	ErrSnapshotLimit      = errors.New("snapshot byte limit reached")
	ErrSnapshotFinished   = errors.New("snapshot builder already finished")
)
View Source
var (
	ErrInvalidMetricName   = errors.New("invalid prometheus metric name")
	ErrInvalidLabels       = errors.New("invalid prometheus labels")
	ErrLabelConflict       = errors.New("prometheus label conflict")
	ErrReservedMetricName  = errors.New("reserved monitor metric name")
	ErrNonMonotonicCounter = errors.New("non-monotonic counter operation")
)
View Source
var ErrRemoteWriteBusy = errors.New("remote write already in progress")

ErrRemoteWriteBusy reports that another Remote Write attempt is active.

View Source
var (
	ErrRetiredPayloadBusy = errors.New("retired exporter payload is still in use")
)

Functions

func AddCounter

func AddCounter(name string, delta int64)

AddCounter adds a specific value to a counter

func DecrementCounter

func DecrementCounter(name string)

DecrementCounter decrements a counter by 1

func DecrementLabeledCounter

func DecrementLabeledCounter(name string, labels ...string)

DecrementLabeledCounter decrements a labeled counter

func DeleteLabeledCounter

func DeleteLabeledCounter(name string, labels ...string)

DeleteLabeledCounter deletes a specific labeled counter

func EncodeRegistrySnapshot added in v0.3.0

func EncodeRegistrySnapshot(w io.Writer, value *RegistrySnapshot) error

EncodeRegistrySnapshot streams a canonical registry snapshot to w.

func ForceWrite

func ForceWrite() error

ForceWrite immediately writes all current metrics to the remote endpoint This is useful for health checks and testing Concurrent calls return ErrRemoteWriteBusy without starting snapshot or network work.

func GetCounter

func GetCounter(name string) int64

GetCounter gets the current value of a counter

func GetLabeledCounter

func GetLabeledCounter(name string, labels ...string) int64

GetLabeledCounter gets the current value of a labeled counter

func GetOutboundIPv4

func GetOutboundIPv4() (string, error)

GetOutboundIPv4 gets the outbound IPv4 address of the local machine

func GetProcessMemory

func GetProcessMemory() (alloc, sys, heapInUse uint64)

GetProcessMemory returns current process memory usage

func GetStatus

func GetStatus() map[string]interface{}

GetStatus returns the current status of the monitoring system

func HealthCheck

func HealthCheck() error

HealthCheck performs a health check on the monitoring system

func IncrementCounter

func IncrementCounter(name string)

IncrementCounter increments a counter by 1

func IncrementLabeledCounter

func IncrementLabeledCounter(name string, labels ...string)

IncrementLabeledCounter increments a labeled counter labels should be provided as [key1, value1, key2, value2, ...]

func Init

func Init(config Config) error

Init initializes the global monitoring system

func ObserveHistogram

func ObserveHistogram(name string, value float64)

ObserveHistogram records a value in a histogram

func RefreshConnection

func RefreshConnection() error

RefreshConnection attempts to refresh the remote write connection This is useful for DNS changes or network connectivity issues

func RegisterCollector

func RegisterCollector(collector Collector) error

RegisterCollector registers a custom metrics collector

func RegisterHistogramBuckets

func RegisterHistogramBuckets(name string, buckets []float64)

RegisterHistogramBuckets registers custom histogram buckets

func RegisterSystemMetricsCollector

func RegisterSystemMetricsCollector(logger *zap.Logger) error

RegisterSystemMetricsCollector registers the system metrics collector with the global monitor

func SetCounter

func SetCounter(name string, value int64)

SetCounter sets a counter to a specific value

func SetLabeledCounter

func SetLabeledCounter(name string, value float64, labels ...string)

SetLabeledCounter sets a labeled counter to a specific value

func Shutdown

func Shutdown()

Shutdown shuts down the global monitoring system

func TriggerGC

func TriggerGC()

TriggerGC triggers garbage collection

func TryAddCounter added in v0.2.0

func TryAddCounter(name string, delta int64) error

TryAddCounter adds a non-negative value to a counter and returns validation errors.

func TryDecrementLabeledCounter added in v0.2.0

func TryDecrementLabeledCounter(name string, labels ...string) error

TryDecrementLabeledCounter rejects a non-monotonic labeled-counter operation.

func TryIncrementLabeledCounter added in v0.2.0

func TryIncrementLabeledCounter(name string, labels ...string) error

TryIncrementLabeledCounter increments a labeled counter and returns validation errors.

func TrySetLabeledCounter added in v0.2.0

func TrySetLabeledCounter(name string, value float64, labels ...string) error

TrySetLabeledCounter sets a labeled gauge and returns validation errors.

Types

type AggregationConfig added in v0.3.0

type AggregationConfig struct {
	Providers        []SnapshotProvider
	SnapshotCacheTTL time.Duration
	GatherTimeout    time.Duration
	Limits           AggregationLimits
}

AggregationConfig configures snapshot providers and bounded generation work.

func DefaultAggregationConfig added in v0.3.0

func DefaultAggregationConfig() AggregationConfig

DefaultAggregationConfig returns finite defaults for aggregation work.

type AggregationLimits added in v0.3.0

type AggregationLimits struct {
	MaxSources                   int64
	MaxSourceIDBytes             int64
	MaxFamilies                  int64
	MaxSeries                    int64
	MaxExpandedSeries            int64
	MaxSnapshotBytes             int64
	MaxLabelsPerSeries           int64
	MaxLabelBytesPerSeries       int64
	MaxHistogramBucketsPerSeries int64
	MaxTotalHistogramBuckets     int64
}

AggregationLimits bounds one fully merged snapshot generation. Zero fields use DefaultAggregationLimits; negative fields are invalid.

func DefaultAggregationLimits added in v0.3.0

func DefaultAggregationLimits() AggregationLimits

DefaultAggregationLimits returns finite limits for one aggregate generation.

type BaseCollector

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

BaseCollector provides basic collector functionality

func NewBaseCollector

func NewBaseCollector(name string, logger *zap.Logger) BaseCollector

NewBaseCollector creates a base collector

func (*BaseCollector) Name

func (b *BaseCollector) Name() string

Name implements Collector interface

type CheckedCollectorRegistrar added in v0.2.0

type CheckedCollectorRegistrar interface {
	RegisterCollectorChecked(collector Collector) error
}

CheckedCollectorRegistrar exposes collector registration errors without changing the legacy Manager interface.

type Collector

type Collector interface {
	Collect() []Metric
	Name() string
}

Collector defines a metrics collector that can provide multiple metrics

type Config

type Config struct {
	// Service identification
	Namespace   string
	Subsystem   string
	ServiceName string

	// Remote write configuration
	RemoteWriteURL      string
	RemoteWriteInterval time.Duration

	// Instance information
	InstanceIP   string
	Version      string
	BuildCommit  string
	BuildTime    string
	CustomLabels map[string]string

	// Optional logger
	Logger       *zap.Logger
	ErrorHandler func(error)

	// Optional Prometheus pull exporter configuration
	PrometheusExporter *PrometheusExporterConfig

	// Optional transport-independent registry limits. Nil preserves the
	// unbounded v0.2.1 registry behavior.
	RegistryLimits *RegistryLimits

	// Optional multi-source structured snapshot aggregation. Nil preserves the
	// v0.2.1 manager paths.
	Aggregation *AggregationConfig

	// DNS resolver options (optional, for advanced use cases)
	DNSEnable          bool
	DNSCacheTTL        time.Duration
	DNSRefreshInterval time.Duration
	DNSTimeout         time.Duration
	DNSUDPServers      []string // e.g. ["1.1.1.1:53", "8.8.8.8:53"]
	DNSTLSServers      []string // e.g. ["1.1.1.1:853", "9.9.9.9:853"]
	DNSDoHEndpoints    []string // e.g. ["https://cloudflare-dns.com/dns-query"]
}

Config defines the configuration for the metrics system

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default configuration

type CounterCollector

type CounterCollector struct {
	BaseCollector
	// contains filtered or unexported fields
}

CounterCollector provides simple counter metrics

func NewCounterCollector

func NewCounterCollector(name string, logger *zap.Logger) *CounterCollector

NewCounterCollector creates a new counter collector

func (*CounterCollector) Add

func (c *CounterCollector) Add(name string, delta int64)

Add adds a specific value to a counter

func (*CounterCollector) Collect

func (c *CounterCollector) Collect() []Metric

Collect implements Collector interface

func (*CounterCollector) CollectTo added in v0.2.0

func (c *CounterCollector) CollectTo(app SnapshotAppender) error

CollectTo appends counter metrics directly to a snapshot.

func (*CounterCollector) Get

func (c *CounterCollector) Get(name string) int64

Get gets the current value of a counter

func (*CounterCollector) Inc

func (c *CounterCollector) Inc(name string)

Inc increments a counter by 1

func (*CounterCollector) Set

func (c *CounterCollector) Set(name string, value int64)

Set sets a counter to a specific value (makes it a gauge)

type DecodeLimits added in v0.3.0

type DecodeLimits struct {
	MaxWireBytes                 int64
	MaxDecodedBytes              int64
	MaxStringBytes               int64
	MaxFamilies                  int64
	MaxSeries                    int64
	MaxTotalLabels               int64
	MaxLabelsPerSeries           int64
	MaxTotalLabelBytes           int64
	MaxLabelBytesPerSeries       int64
	MaxSingleLabelBytes          int64
	MaxHistogramBucketsPerSeries int64
	MaxTotalHistogramBuckets     int64
	MaxExpandedSeries            int64
}

DecodeLimits bounds both the wire payload and the canonical snapshot built from it. Zero fields use DefaultDecodeLimits; negative fields are invalid.

func DefaultDecodeLimits added in v0.3.0

func DefaultDecodeLimits() DecodeLimits

DefaultDecodeLimits returns finite limits suitable for large registries.

type GCStats

type GCStats struct {
	LastGC     time.Time
	NumGC      int64
	PauseTotal time.Duration
}

GCStats represents garbage collection statistics

func ReadGCStats

func ReadGCStats() GCStats

ReadGCStats reads garbage collection statistics

type HistogramCollector

type HistogramCollector struct {
	BaseCollector
	// contains filtered or unexported fields
}

HistogramCollector provides histogram metrics.

func NewHistogramCollector

func NewHistogramCollector(name string, logger *zap.Logger) *HistogramCollector

NewHistogramCollector creates a new histogram collector.

func (*HistogramCollector) Collect

func (h *HistogramCollector) Collect() []Metric

Collect implements Collector using the same structured snapshot as CollectTo.

func (*HistogramCollector) CollectTo added in v0.2.0

func (h *HistogramCollector) CollectTo(app SnapshotAppender) error

CollectTo appends one consistent structured histogram per registered name.

func (*HistogramCollector) Observe

func (h *HistogramCollector) Observe(name string, value float64)

Observe records a value in a histogram.

func (*HistogramCollector) RegisterHistogram

func (h *HistogramCollector) RegisterHistogram(name string, buckets []float64)

RegisterHistogram registers a histogram with specified buckets.

type LabeledCounterCollector

type LabeledCounterCollector struct {
	BaseCollector
	// contains filtered or unexported fields
}

LabeledCounterCollector provides labeled counter metrics

func NewApplicationCollector

func NewApplicationCollector(name string, logger *zap.Logger) *LabeledCounterCollector

NewApplicationCollector creates an application-specific collector

func NewLabeledCounterCollector

func NewLabeledCounterCollector(name string, logger *zap.Logger) *LabeledCounterCollector

NewLabeledCounterCollector creates a new labeled counter collector

func (*LabeledCounterCollector) Collect

func (c *LabeledCounterCollector) Collect() []Metric

Collect implements Collector interface

func (*LabeledCounterCollector) CollectTo added in v0.2.0

CollectTo appends labeled metrics directly to a snapshot. Cleanup still runs after an append error, matching the timing of a completed legacy collection.

func (*LabeledCounterCollector) Dec

func (c *LabeledCounterCollector) Dec(metricName string, labels ...string)

Dec decrements a labeled counter

func (*LabeledCounterCollector) Delete

func (c *LabeledCounterCollector) Delete(metricName string, labels ...string)

Delete removes a specific labeled counter entry

func (*LabeledCounterCollector) ForceCleanup

func (c *LabeledCounterCollector) ForceCleanup()

ForceCleanup forces immediate cleanup regardless of time intervals

func (*LabeledCounterCollector) Get

func (c *LabeledCounterCollector) Get(metricName string, labels ...string) int64

Get gets the current value of a labeled counter

func (*LabeledCounterCollector) Inc

func (c *LabeledCounterCollector) Inc(metricName string, labels ...string)

Inc increments a labeled counter

func (*LabeledCounterCollector) Set

func (c *LabeledCounterCollector) Set(metricName string, value float64, labels ...string)

Set sets a labeled counter to a specific value

func (*LabeledCounterCollector) SetMaxSeries

func (c *LabeledCounterCollector) SetMaxSeries(n int)

SetMaxSeries sets the maximum number of time series (0 means no limit)

func (*LabeledCounterCollector) SetTTL

func (c *LabeledCounterCollector) SetTTL(ttl time.Duration)

SetTTL sets the TTL for time series

type Manager

type Manager interface {
	Start() error
	Stop()
	RegisterCollector(collector Collector)
	GetMetrics() []Metric
}

Manager is the main interface for metrics collection and reporting

func NewManager

func NewManager(config Config) (Manager, error)

NewManager creates a new metrics manager

type Metric

type Metric struct {
	Name       string
	Value      float64
	Labels     map[string]string
	MetricType MetricType
	Timestamp  time.Time
}

Metric represents a single metric data point

type MetricType

type MetricType int

MetricType represents the type of a metric

const (
	Counter MetricType = iota
	Gauge
	Histogram
	Summary
)

type PrometheusExporterConfig added in v0.2.0

type PrometheusExporterConfig struct {
	ListenAddress          string
	Path                   string
	SnapshotCacheTTL       time.Duration
	MaxConcurrentScrapes   int
	MaxStoredSeries        int
	MaxEstimatedStoreBytes int64
	MaxSnapshotBytes       int64
	MaxLabelsPerSeries     int
	MaxLabelBytesPerSeries int
	RemoteWriteBatchSeries int
	ReadHeaderTimeout      time.Duration
	WriteTimeout           time.Duration
	IdleTimeout            time.Duration
	ShutdownTimeout        time.Duration
}

PrometheusExporterConfig configures the optional Prometheus pull exporter.

type RegistryFamily added in v0.3.0

type RegistryFamily struct {
	Name       string
	MetricType MetricType
	Samples    []RegistrySample
}

RegistryFamily groups samples that share a business metric name and type.

type RegistryHistogram added in v0.3.0

type RegistryHistogram struct {
	Count   uint64
	Sum     float64
	Buckets []RegistryHistogramBucket
}

RegistryHistogram preserves a classic histogram's count, sum, and finite cumulative buckets.

type RegistryHistogramBucket added in v0.3.0

type RegistryHistogramBucket struct {
	UpperBound      float64
	CumulativeCount uint64
}

RegistryHistogramBucket is one finite upper bound and cumulative count.

type RegistryLimits added in v0.3.0

type RegistryLimits struct {
	MaxStoredSeries        int
	MaxEstimatedStoreBytes int64
	MaxSnapshotSeries      int
	MaxSnapshotBytes       int64
	MaxLabelsPerSeries     int
	MaxLabelBytesPerSeries int
}

RegistryLimits bounds the transport-independent in-process registry.

func DefaultRegistryLimits added in v0.3.0

func DefaultRegistryLimits() RegistryLimits

DefaultRegistryLimits returns the limits used for zero-valued fields when registry limits are explicitly enabled.

type RegistrySample added in v0.3.0

type RegistrySample struct {
	Value     float64
	Labels    []SnapshotLabel
	Histogram *RegistryHistogram
}

RegistrySample is one scalar or histogram sample with business labels only.

type RegistrySnapshot added in v0.3.0

type RegistrySnapshot struct {
	SchemaVersion string
	CapturedAt    time.Time
	Namespace     string
	Subsystem     string
	// contains filtered or unexported fields
}

RegistrySnapshot is an immutable point-in-time view of business metrics. Families returns caller-owned copies for public inspection.

func DecodeRegistrySnapshot added in v0.3.0

func DecodeRegistrySnapshot(r io.Reader, limits DecodeLimits) (*RegistrySnapshot, error)

DecodeRegistrySnapshot reads one complete wire payload and rebuilds the private canonical backing through snapshotBuilder validation.

func GatherRegistrySnapshot added in v0.3.0

func GatherRegistrySnapshot(ctx context.Context) (*RegistrySnapshot, error)

GatherRegistrySnapshot gathers from the initialized global manager.

func (*RegistrySnapshot) Families added in v0.3.0

func (s *RegistrySnapshot) Families() []RegistryFamily

Families returns a deep-copy view that callers may retain or mutate without changing the snapshot.

type RegistrySnapshotGatherer added in v0.3.0

type RegistrySnapshotGatherer interface {
	GatherRegistrySnapshot(context.Context) (*RegistrySnapshot, error)
}

RegistrySnapshotGatherer exposes business metrics as an owned structured snapshot without changing the legacy Manager interface.

type SnapshotAppender added in v0.2.0

type SnapshotAppender interface {
	AppendScalar(name string, metricType MetricType, value float64, labels []SnapshotLabel) error
	AppendHistogram(name string, histogram *dto.Histogram, labels []SnapshotLabel) error
}

SnapshotAppender is valid only for the synchronous duration of a SnapshotCollector.CollectTo call. Collectors must not retain it or use it concurrently.

type SnapshotCollector added in v0.2.0

type SnapshotCollector interface {
	Collector
	CollectTo(SnapshotAppender) error
}

type SnapshotEmitFunc added in v0.3.0

type SnapshotEmitFunc func(SourceSnapshotResult) error

SnapshotEmitFunc synchronously consumes one source snapshot result.

type SnapshotLabel added in v0.2.0

type SnapshotLabel struct {
	Name  string
	Value string
}

SnapshotLabel is the shared label representation used by validation and later snapshot encoders.

type SnapshotProvider added in v0.3.0

type SnapshotProvider interface {
	// Name is the provider's bounded control-plane identity. It is not exported
	// as a Prometheus label.
	Name() string
	// GatherSnapshots must call emit synchronously and serially, must not retain
	// it, and must not call it after GatherSnapshots returns. A result containing
	// Err reports one failed source: that source is skipped and the successfully
	// built generation is partial. Returning an error from GatherSnapshots is a
	// provider-fatal failure and rejects the entire generation. Providers must
	// respond to ctx cancellation promptly; the SDK cannot forcibly stop one
	// that ignores the context.
	GatherSnapshots(ctx context.Context, emit SnapshotEmitFunc) error
}

SnapshotProvider emits source snapshots during one gather operation.

type SourceDescriptor added in v0.3.0

type SourceDescriptor struct {
	SourceID     string
	ServiceName  string
	InstanceIP   string
	CustomLabels map[string]string
}

SourceDescriptor supplies control-plane identity and exported source labels.

type SourceSnapshotResult added in v0.3.0

type SourceSnapshotResult struct {
	Source   SourceDescriptor
	Snapshot *RegistrySnapshot
	Err      error
}

SourceSnapshotResult carries one source identity and exactly one of Snapshot or Err. Snapshot is a successful source result. Err is a single-source failure: aggregation skips that source and marks an otherwise successful generation partial.

type SystemMetricsCollector

type SystemMetricsCollector struct {
	BaseCollector
}

SystemMetricsCollector collects basic system metrics

func NewSystemMetricsCollector

func NewSystemMetricsCollector(logger *zap.Logger) *SystemMetricsCollector

NewSystemMetricsCollector creates a new system metrics collector

func (*SystemMetricsCollector) Collect

func (s *SystemMetricsCollector) Collect() []Metric

Collect implements Collector interface

func (*SystemMetricsCollector) CollectTo added in v0.2.0

func (s *SystemMetricsCollector) CollectTo(app SnapshotAppender) error

CollectTo appends system metrics directly to a snapshot.

Jump to

Keyboard shortcuts

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