servicehealth

package
v1.4.29 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package servicehealth stores and aggregates the OSS log and internal health projection.

Index

Constants

View Source
const (
	DefaultIntervalSeconds = 60
	DefaultWindowSeconds   = 300
	MinIntervalSeconds     = 30
	MaxIntervalSeconds     = 900
	MinWindowSeconds       = 60
	MaxWindowSeconds       = 3600
	BucketDuration         = time.Minute
	MaxServicesPerSnapshot = 500
	MaxSnapshots           = 60
	MaxSnapshotAge         = 24 * time.Hour
	MaxSnapshotBytes       = 4 << 20
	MaxStateBytes          = 4 << 20
	MaxLogBuckets          = 100000
	MaxPatternIDsPerBucket = 256
	MaxPatternIDsPerWindow = 1024
	MaxStateSources        = 1024
	MaxLogRetention        = time.Duration(MaxWindowSeconds)*time.Second + 2*BucketDuration
	MaxPremiumSources      = 16
	MaxExternalRequests    = 64
	MaxRequestsPerSource   = 8
	MaxRowsPerSource       = 10000
	MaxResponseBytes       = 1 << 20
	MaxCumulativeBytes     = 16 << 20
	MaxConcurrency         = 2
	MaxRequestDuration     = 10 * time.Second
)
View Source
const (
	MaxEvidencePerService = 64
)
View Source
const ScheduleJobName = "service-health"

ScheduleJobName is the stable ownership key for Service Health collection.

Variables

View Source
var (
	ErrConflict   = errors.New("service health settings changed concurrently")
	ErrNoStorage  = errors.New("service health storage unavailable")
	ErrBufferFull = errors.New("service health observation buffer is full")
)

Functions

func Organizations

func Organizations(ctx context.Context) ([]string, error)

Organizations returns normalized, deduplicated organizations to collect. The OSS default organization is always included for backward compatibility.

func SetOrganizationLister

func SetOrganizationLister(lister OrganizationLister)

SetOrganizationLister installs the process-wide organization enumeration hook. Passing nil restores the single-tenant OSS default.

func ValidateSettings

func ValidateSettings(settings Settings) error

ValidateSettings rejects values outside the server-owned bounds.

Types

type AssessmentRequest

type AssessmentRequest struct {
	OrgID       string
	WindowStart time.Time
	WindowEnd   time.Time
	Evidence    []core.SignalEvidence
	Inputs      []core.HealthAssessmentInput
	Services    []ServiceSnapshot
}

AssessmentRequest contains only validated evidence and the current OSS snapshots. Assessors may enrich these snapshots but cannot replace them.

type Capability

type Capability = core.HealthCapability

type Collector

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

Collector builds and persists OSS snapshots without external reads.

func NewCollector

func NewCollector(options CollectorOptions) *Collector

NewCollector creates a bounded snapshot collector.

func (*Collector) Collect

func (collector *Collector) Collect(ctx context.Context, orgID string) (SnapshotEnvelope, error)

Collect builds one snapshot under the captured settings revision and saves it atomically.

type CollectorOptions

type CollectorOptions struct {
	Manager           *Manager
	Store             storage.Provider
	Services          func() []ServiceMetadata
	Patterns          func() []PatternMetadata
	SourceIDs         []string
	Providers         []core.HealthProvider
	ProviderSourceIDs []string
	Assessor          HealthAssessor
	EnrichmentAccess  EnrichmentAccess
	Now               func() time.Time
}

CollectorOptions supplies trusted, already-local readers. No option can pull a signal source.

type CoverageSummary

type CoverageSummary struct {
	TotalServices    int  `json:"total_services"`
	ObservedServices int  `json:"observed_services"`
	Partial          bool `json:"partial"`
}

type DomainSnapshot

type DomainSnapshot struct {
	Name          string `json:"name"`
	Severity      string `json:"severity"`
	ServiceCount  int    `json:"service_count"`
	ObservedCount int    `json:"observed_count"`
	AffectedCount int    `json:"affected_count"`
}

type EnrichmentAccess

type EnrichmentAccess func(context.Context, string) error

EnrichmentAccess revalidates whether premium enrichment may be persisted.

type HealthAssessor

type HealthAssessor interface {
	Assess(context.Context, AssessmentRequest) ([]core.HealthAssessment, error)
}

HealthAssessor computes optional source-neutral enrichment over validated evidence.

type Manager

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

Manager is the storage-backed Service Health recorder and snapshot store.

func NewManager

func NewManager(store storage.Provider) *Manager

NewManager constructs a manager over the shared storage provider.

func (*Manager) LoadSettings

func (manager *Manager) LoadSettings(orgID string) (Settings, error)

LoadSettings returns defaults only for an absent record; storage and decode failures are returned so callers never mistake an outage for defaults.

func (*Manager) LoadSnapshot

func (manager *Manager) LoadSnapshot(orgID string) (SnapshotEnvelope, bool, error)

LoadSnapshot returns the newest snapshot for exactly one org.

func (*Manager) QueryWindow

func (manager *Manager) QueryWindow(orgID string, end time.Time, window time.Duration) ([]WindowAggregate, []SourceStatus, error)

QueryWindow sums fixed buckets; catalog lifetime Pattern.Count is never read.

func (*Manager) RecordLogHealth

func (manager *Manager) RecordLogHealth(_ context.Context, observation core.LogHealthObservation) error

RecordLogHealth buffers one safe worker observation in an indexed minute bucket. Durability is intentionally interval-based: QueryWindow flushes pending deltas, so a process crash can lose at most the observations since the last collection.

func (*Manager) RecordSourceHealth

func (manager *Manager) RecordSourceHealth(_ context.Context, observation core.SourceHealthObservation) error

RecordSourceHealth stores attempt/success separately and allowlists error classes.

func (*Manager) SaveSnapshot

func (manager *Manager) SaveSnapshot(orgID string, snapshot SnapshotEnvelope) error

SaveSnapshot appends idempotently and rejects a result from an older settings revision.

func (*Manager) SetSnapshotProjection

func (manager *Manager) SetSnapshotProjection(projection SnapshotProjection)

SetSnapshotProjection installs an instance-scoped, concurrent-safe read projection.

func (*Manager) SnapshotFor

func (manager *Manager) SnapshotFor(ctx context.Context, orgID string) (SnapshotEnvelope, error)

SnapshotFor reads and projects the newest persisted snapshot for one request org. It never aggregates buckets or calls a source.

func (*Manager) SnapshotOrEmpty

func (manager *Manager) SnapshotOrEmpty(orgID string) (SnapshotEnvelope, error)

SnapshotOrEmpty preserves the context-free OSS read contract.

func (*Manager) UpdateSettings

func (manager *Manager) UpdateSettings(orgID string, next Settings) (Settings, error)

UpdateSettings performs an optimistic revision update and persists before returning.

type OrganizationLister

type OrganizationLister func(context.Context) ([]string, error)

OrganizationLister returns organizations that need scheduled snapshots. Out-of-tree runtimes may register their authoritative organization catalog.

type PatternMetadata

type PatternMetadata struct {
	OrgID    string
	Service  string
	LastSeen time.Time
}

PatternMetadata contributes internal presence only; Count is intentionally absent.

type Runtime

type Runtime struct {
	Manager *Manager
	Job     scheduler.Job
}

Runtime carries the manager mounted by routes and its shared scheduler job.

func NewRuntime

func NewRuntime(options RuntimeOptions) *Runtime

NewRuntime constructs one manager and one organization-aware scheduler job. The caller installs any organization lister and ownership predicate before registering Job with the shared scheduler.

type RuntimeOptions

type RuntimeOptions struct {
	Manager           *Manager
	Store             storage.Provider
	Services          func() []ServiceMetadata
	Patterns          func() []PatternMetadata
	SourceIDs         []string
	Providers         []core.HealthProvider
	ProviderSourceIDs []string
	Assessor          HealthAssessor
	EnrichmentAccess  EnrichmentAccess
	Projection        SnapshotProjection
	Now               func() time.Time
}

RuntimeOptions supplies generic local readers for one Service Health runtime.

type ServiceMetadata

type ServiceMetadata struct {
	OrgID  string
	Name   string
	Domain string
	Kind   string
}

ServiceMetadata is the source-neutral catalog view used by the collector.

type ServiceSnapshot

type ServiceSnapshot struct {
	OrgID           string                              `json:"org_id"`
	Service         string                              `json:"service"`
	Domain          string                              `json:"domain"`
	Kind            string                              `json:"kind"`
	Severity        string                              `json:"severity"`
	BaseSeverity    string                              `json:"base_severity,omitempty"`
	AssessmentBasis string                              `json:"assessment_basis"`
	Logs            WindowAggregate                     `json:"logs"`
	Availability    map[string]core.MeasureAvailability `json:"availability"`
	ActiveIncidents *int                                `json:"active_incidents"`
	Evidence        []core.SignalEvidence               `json:"evidence,omitempty"`
	Assessment      *core.HealthAssessment              `json:"assessment,omitempty"`
}

type Settings

type Settings struct {
	IntervalSeconds int    `json:"interval_seconds"`
	WindowSeconds   int    `json:"window_seconds"`
	Revision        uint64 `json:"revision"`
	Diagnostic      string `json:"diagnostic,omitempty"`
}

Settings is the always-enabled runtime timing configuration.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings returns the fresh-install timing values.

type SnapshotEnvelope

type SnapshotEnvelope struct {
	SnapshotID       string            `json:"snapshot_id"`
	GeneratedAt      time.Time         `json:"generated_at"`
	LatestAttempt    time.Time         `json:"latest_attempt"`
	LatestSuccess    time.Time         `json:"latest_success,omitempty"`
	NextCollectionAt time.Time         `json:"next_collection_at"`
	SettingsRevision uint64            `json:"settings_revision"`
	WindowSeconds    int               `json:"window_seconds"`
	Services         []ServiceSnapshot `json:"services"`
	Domains          []DomainSnapshot  `json:"domains"`
	Facets           map[string]int    `json:"facets"`
	Coverage         CoverageSummary   `json:"coverage"`
	Capabilities     []Capability      `json:"capabilities"`
	PendingSettings  *Settings         `json:"pending_settings,omitempty"`
}

SnapshotEnvelope is the durable, API-ready result for one org and revision.

type SnapshotProjection

type SnapshotProjection func(context.Context, string, SnapshotEnvelope) (SnapshotEnvelope, error)

SnapshotProjection applies request-org access policy to a snapshot at read time. A nil projection preserves the OSS response exactly.

type SourceStatus

type SourceStatus struct {
	SourceID      string    `json:"source_id"`
	LatestAttempt time.Time `json:"latest_attempt"`
	LatestSuccess time.Time `json:"latest_success,omitempty"`
	ErrorClass    string    `json:"error_class,omitempty"`
}

SourceStatus is safe operational source coverage with no backend message.

type ValidationError

type ValidationError struct {
	Fields map[string]string `json:"fields"`
}

ValidationError carries field-specific settings errors.

func (*ValidationError) Error

func (err *ValidationError) Error() string

type WindowAggregate

type WindowAggregate struct {
	Service           string           `json:"service"`
	SourceID          string           `json:"source_id"`
	MatchedLogs       int64            `json:"matched_logs"`
	UniquePatterns    int              `json:"unique_patterns"`
	NewPatterns       int              `json:"new_patterns"`
	UnknownPatterns   int              `json:"unknown_patterns"`
	SpikingPatterns   int              `json:"spiking_patterns"`
	SeverityCounts    map[string]int64 `json:"severity_counts"`
	LatestObservation time.Time        `json:"latest_observation,omitempty"`
	Estimated         bool             `json:"estimated"`
	Truncated         bool             `json:"truncated,omitempty"`
	PartialReason     string           `json:"partial_reason,omitempty"`
}

WindowAggregate is the bounded count-only log view for one service/source.

Jump to

Keyboard shortcuts

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