telemetry

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package telemetry collects bounded, best-effort operational observations. A Collector owns its HTTP metrics independently of Prometheus and snapshots configuration at construction. Register its Report method with a recorder and the collector itself as an HTTP request observer. SetRoutes may be called once, before observation begins, with the assembled router's declared metadata.

New adds an optional Engine for receipt-backed persistence, bounded reads and incident episodes. Apply Migrations explicitly in its selected schema, stop producers before Close, and retain borrowed dependencies until Done closes. Configured application assembly registers the reporter and owns this ordering.

Collection performs no persistence. Browser reports are untrusted; applications still own authentication, authorization, CSRF, body limits and rate limiting. Loss counters are operational estimates, not an audit of unique lost requests: cumulative bucket snapshots and simultaneous capacity limits can overlap.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlertStateCodec

func AlertStateCodec() codec.Codec[AlertState]

AlertStateCodec applies the generated membership rule at both SQL boundaries. Example: AlertStateCodec()

func BrowserCodeCodec

func BrowserCodeCodec() codec.Codec[BrowserCode]

BrowserCodeCodec applies the generated membership rule at both SQL boundaries. Example: BrowserCodeCodec()

func KernelModule

func KernelModule(name foundation.ProviderID, key foundation.Key[*Engine], kernels []foundation.KernelKind, requires []foundation.ProviderID, construct func(foundation.Resolver) (*Engine, error)) foundation.Module

KernelModule registers an engine and its cleanup before starting a tracked capture task. Empty kernels select HTTP, Worker and Scheduler; CLI-only and Start without selected kernels expose reads but do not run a periodic loop. Requires must include every borrowed resource owner. Cleanup waits for Done even after its deadline, preserving dependencies under uncooperative callbacks.

func Migrations

func Migrations() []migrate.Definition

Migrations returns owned, immutable history for a fresh telemetry store. Register once and apply explicitly with the ordinary migration runner in the same selected schema used by telemetry. This function performs no I/O and neither copies nor modifies application-owned developer telemetry tables.

func RuleCodec

func RuleCodec() codec.Codec[Rule]

RuleCodec applies the generated membership rule at both SQL boundaries. Example: RuleCodec()

func SourceCodec

func SourceCodec() codec.Codec[Source]

SourceCodec applies the generated membership rule at both SQL boundaries. Example: SourceCodec()

Types

type Acknowledgement

type Acknowledgement struct {
	Key     AlertKey
	Episode Episode
}

Acknowledgement identifies the incident episode acknowledged in the caller's transaction.

type Alert

type Alert struct {
	Key             AlertKey
	RunID           model.ID[Run]
	Episode         Episode
	Rule            Rule
	State           AlertState
	FirstAt, LastAt temporal.DateTime
	RecoveredAt     value.Nullable[temporal.DateTime]
}

Alert is an incident snapshot without application actor attribution.

type AlertKey

type AlertKey string

AlertKey is a lowercase SHA-256 incident identity. Parse external values with ParseAlertKey; conversion from string alone does not validate it.

func ParseAlertKey

func ParseAlertKey(text string) (AlertKey, error)

ParseAlertKey validates a canonical lowercase SHA-256 identity.

type AlertPolicy

type AlertPolicy struct {
	Enabled                          bool
	Rules                            []Rule
	Thresholds                       Thresholds
	SustainCaptures, RecoverCaptures int
}

AlertPolicy selects built-in rules and capture-count sustain/recovery periods. Disabled policies may omit thresholds and counts entirely.

func (AlertPolicy) Validate

func (p AlertPolicy) Validate() error

Validate checks rule identity/uniqueness and explicit thresholds/counts when enabled or supplied. A disabled zero policy is valid and supplies no defaults.

type AlertQuery

type AlertQuery struct {
	State value.Optional[AlertState]
	Page  orm.PageRequest
}

AlertQuery optionally filters incident state and selects a bounded page.

type AlertState

type AlertState string

AlertState identifies an incident's state.

const (
	AlertStateOpen         AlertState = "open"
	AlertStateAcknowledged AlertState = "acknowledged"
	AlertStateRecovered    AlertState = "recovered"
)

func AlertStateValues

func AlertStateValues() []AlertState

AlertStateValues returns declared values in source order, with independent slice ownership. Example: AlertStateValues()

func ParseAlertState

func ParseAlertState(text string) (AlertState, error)

ParseAlertState decodes and validates an enum's text representation. Example: ParseAlertState(text)

func (AlertState) EnumDescriptor

func (AlertState) EnumDescriptor() enum.Descriptor[AlertState]

EnumDescriptor describes this enum type independently of the receiver's value.

func (AlertState) IsValid

func (v AlertState) IsValid() bool

IsValid checks membership; a Go cast alone does not validate external values.

func (AlertState) MarshalJSON

func (v AlertState) MarshalJSON() ([]byte, error)

MarshalJSON encodes a validated enum as JSON.

func (AlertState) MarshalText

func (v AlertState) MarshalText() ([]byte, error)

MarshalText encodes a validated enum as text.

func (*AlertState) Scan

func (v *AlertState) Scan(source any) error

Scan changes the receiver only after successful decoding. SQL NULL is rejected.

func (*AlertState) UnmarshalJSON

func (v *AlertState) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes validated JSON and rejects null.

func (*AlertState) UnmarshalText

func (v *AlertState) UnmarshalText(data []byte) error

UnmarshalText decodes validated enum text and changes the receiver only on success.

func (AlertState) Validate

func (v AlertState) Validate() error

Validate reports invalid values without formatting the input.

func (AlertState) Value

func (v AlertState) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer through the shared typed codec.

type BrowserCode

type BrowserCode string

BrowserCode is an allowlisted exception class; exception messages are absent.

const (
	BrowserCodeError              BrowserCode = "Error"
	BrowserCodeTypeError          BrowserCode = "TypeError"
	BrowserCodeRangeError         BrowserCode = "RangeError"
	BrowserCodeReferenceError     BrowserCode = "ReferenceError"
	BrowserCodeSyntaxError        BrowserCode = "SyntaxError"
	BrowserCodeURIError           BrowserCode = "URIError"
	BrowserCodeEvalError          BrowserCode = "EvalError"
	BrowserCodeUnhandledRejection BrowserCode = "UnhandledRejection"
	BrowserCodeReactBoundary      BrowserCode = "ReactBoundary"
)

func BrowserCodeValues

func BrowserCodeValues() []BrowserCode

BrowserCodeValues returns declared values in source order, with independent slice ownership. Example: BrowserCodeValues()

func ParseBrowserCode

func ParseBrowserCode(text string) (BrowserCode, error)

ParseBrowserCode decodes and validates an enum's text representation. Example: ParseBrowserCode(text)

func (BrowserCode) EnumDescriptor

func (BrowserCode) EnumDescriptor() enum.Descriptor[BrowserCode]

EnumDescriptor describes this enum type independently of the receiver's value.

func (BrowserCode) IsValid

func (v BrowserCode) IsValid() bool

IsValid checks membership; a Go cast alone does not validate external values.

func (BrowserCode) MarshalJSON

func (v BrowserCode) MarshalJSON() ([]byte, error)

MarshalJSON encodes a validated enum as JSON.

func (BrowserCode) MarshalText

func (v BrowserCode) MarshalText() ([]byte, error)

MarshalText encodes a validated enum as text.

func (*BrowserCode) Scan

func (v *BrowserCode) Scan(source any) error

Scan changes the receiver only after successful decoding. SQL NULL is rejected.

func (*BrowserCode) UnmarshalJSON

func (v *BrowserCode) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes validated JSON and rejects null.

func (*BrowserCode) UnmarshalText

func (v *BrowserCode) UnmarshalText(data []byte) error

UnmarshalText decodes validated enum text and changes the receiver only on success.

func (BrowserCode) Validate

func (v BrowserCode) Validate() error

Validate reports invalid values without formatting the input.

func (BrowserCode) Value

func (v BrowserCode) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer through the shared typed codec.

type BrowserError

type BrowserError struct {
	Portal  Portal
	Release Release
	Code    BrowserCode
	Frames  []BrowserFrame
}

BrowserError supplies only an allowlisted portal, current release, class and at most twenty frames. It carries no browser messages, URLs or payloads.

type BrowserFrame

type BrowserFrame struct {
	File         string
	Line, Column int
}

BrowserFrame is a location in a portal's deployed JavaScript asset. File must be exactly portal/_assets/basename.js, with no URL, encoding or traversal.

type BrowserPolicy

type BrowserPolicy struct {
	Enabled bool
	Portals []Portal
}

BrowserPolicy enables anonymous admission for an explicit portal allowlist.

func (BrowserPolicy) Validate

func (p BrowserPolicy) Validate() error

Validate checks the explicit browser allowlist, including duplicate portals.

type Collector

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

Collector admits observations into bounded memory. It owns an independent RequestMetrics and never drains a recorder or cumulative Prometheus owner. Observation methods are concurrency-safe, do no storage I/O, and must return before request ownership ends. The injected clock must return promptly and support concurrent calls; clock panic/Goexit is contained by temporal.Now. Do not copy a Collector. Construct it with NewCollector.

func NewCollector

func NewCollector(c CollectorConfig, source clock.Clock) (*Collector, error)

NewCollector validates and snapshots configuration and reads the explicit clock to create a UUIDv7 run identity. It starts no background runtime owner. A nil clock is invalid; pass clock.System{} for ordinary application time.

Example
package main

import (
	"fmt"
	"time"

	"github.com/weiloon1234/Foundry-Go/clock"
	"github.com/weiloon1234/Foundry-Go/http"
	"github.com/weiloon1234/Foundry-Go/observability"
	"github.com/weiloon1234/Foundry-Go/telemetry"
)

func main() {
	collector, err := telemetry.NewCollector(telemetry.CollectorConfig{
		Instance: "worker-1", Release: "release-1",
		MaxSeries: 1024, MaxEvents: 1024, MaxPendingBatches: 6,
		PendingRetention: time.Hour,
	}, clock.System{})
	if err != nil {
		panic(err)
	}
	// Register these with the existing HTTP server and recorder during assembly.
	var observer http.SecurityRequestObserver = collector
	var reporter observability.Reporter = collector.Report
	fmt.Println(observer != nil, reporter != nil, !collector.RunID().IsZero())
}
Output:
true true true

func (*Collector) ObserveRequest

func (c *Collector) ObserveRequest(ctx context.Context, e http.RequestEvent)

ObserveRequest records traffic, including excluded routes. Exclusions apply to later alert/read selection, while security classification is independent.

func (*Collector) ObserveSecurityRequest

func (c *Collector) ObserveSecurityRequest(_ context.Context, e http.SecurityRequestEvent)

ObserveSecurityRequest classifies before discarding the raw path. Only a structural category, declared route, correlation ID and trusted-proxy address survive; paths, queries and credentials never enter retained detail.

func (*Collector) RecordBrowser

func (c *Collector) RecordBrowser(_ context.Context, report BrowserError) error

RecordBrowser validates and snapshots an untrusted browser observation into memory. Disabled/invalid intake returns a safe validation error; capacity loss returns nil and increments Dropped. Success is not a persistence receipt.

func (*Collector) Report

Report accepts safe recorder diagnostics at HTTP/job/schedule business boundaries. Resource/provider reports, app exclusions and telemetry's own operations are ignored to prevent recursive reporting. Fault messages and attributes are not retained. Queue-full admission counts loss and returns nil.

func (*Collector) RunID

func (c *Collector) RunID() model.ID[Run]

RunID returns this collector's stable, model-owned process identity.

func (*Collector) SetRoutes

func (c *Collector) SetRoutes(routes []http.RouteInfo) error

SetRoutes snapshots declared route templates once before any observation or capture. Duplicate IDs fail atomically. Without an inventory, metric paths remain empty; observations still use validated declared route identities.

type CollectorConfig

type CollectorConfig struct {
	Instance                                Instance
	Release                                 Release
	MaxSeries, MaxEvents, MaxPendingBatches int
	PendingRetention                        time.Duration
	Routes                                  RoutePolicy
	Browser                                 BrowserPolicy
}

CollectorConfig supplies identity and memory bounds. No zero-value defaults or alert thresholds are inferred. PendingRetention is one minute to one hour.

func (CollectorConfig) Validate

func (c CollectorConfig) Validate() error

Validate checks identity, nested policies and Starter-compatible memory ranges: series/events 1..4096, pending batches 1..60, retention one minute to one hour.

type Config

type Config struct {
	FlushInterval, FlushTimeout, DrainTimeout time.Duration
	Retention                                 RetentionPolicy
	Alerts                                    AlertPolicy
	Reads                                     ReadLimits
}

Config supplies future engine timing, retention, alert and read policy without starting an engine. FlushInterval is one second to one minute. Timeouts must be positive. Retry/receipt horizons additionally require the collector's retention at the eventual engine construction boundary; this value alone cannot check it.

func (Config) Validate

func (c Config) Validate() error

Validate checks timing, nested policies, and read caps against storage caps.

type Dependencies

type Dependencies struct {
	DB        *database.DB
	Schema    string
	Recorder  *observability.Recorder
	Readiness *diagnostics.Runtime
	Clock     clock.Clock
	Logger    *slog.Logger
}

Dependencies are borrowed for the Engine's entire lifetime, through Done. Schema is explicit. Recorder must have the collector's reporter registered by its owner. Nil Readiness means unavailable; nil Logger disables failure logs.

type DependencyHealth

type DependencyHealth struct {
	ID    health.ProbeID
	State health.State
}

DependencyHealth retains a probe identity and state, never dependency errors.

type Detail

type Detail struct {
	Frames    []Frame
	RequestID attribution.RequestID
	TraceID   tracing.TraceID
	Path      string
	ClientIP  value.Optional[netip.Addr] `json:",omitzero"`
	Untrusted bool
}

Detail contains redacted issue evidence. ClientIP is protected detail, never a metric label; callers must authorize access before exposing it.

type Engine

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

Engine owns one collector, capture loop and final drain. It never closes its dependencies. Run is single-use; its return does not finalize the collector. Call Close after producers stop, and retain dependencies until Done closes. Do not copy an Engine.

func New

func New(c *Collector, deps Dependencies, config Config) (*Engine, error)

New validates and snapshots policy before claiming the collector. It performs no database I/O and starts no work. A collector has exactly one Engine/storage owner, including when that owner is closed. Apply Migrations separately.

func (*Engine) AcknowledgeIn

func (e *Engine) AcknowledgeIn(ctx context.Context, tx *database.Tx, key AlertKey) (Acknowledgement, error)

AcknowledgeIn locks and acknowledges the current incident episode in the caller's transaction on this engine's database. It performs no authorization: the caller must first lock/recheck its actor and persist attribution using the returned episode in that same transaction. Success does not promise commit. Recovered incidents conflict. Repeated acknowledgement returns the same episode.

func (*Engine) Close

func (e *Engine) Close(ctx context.Context) error

Close seals intake and API admission once, cancels Run, and starts finalization. Its context bounds only this caller's wait. Finalization waits for actual work exit, performs a final capture and a DrainTimeout-limited FIFO drain, and counts remaining batches as best-effort shutdown loss. Late reports also count loss. Repeated Close calls return the same completed result; Done is the ownership barrier.

func (*Engine) Done

func (e *Engine) Done() <-chan struct{}

Done closes only after the loop, admitted API work and finalization have actually exited. A Close deadline never releases ownership early.

func (*Engine) Flush

func (e *Engine) Flush(ctx context.Context, token telemetrytest.Token) error

Flush captures once and drains pending batches in FIFO order for framework test helpers. Consumers use testkit/telemetry.Flush; the internal token prevents production callers from acquiring this capability. It starts no loop and works alongside Run or before Run starts. Close rejects new flushes and waits for admitted flushes before final capture and dependency cleanup.

DrainTimeout bounds cooperative capture and storage work, with FlushTimeout still bounding each write. Callbacks retain ownership until they actually exit, even beyond the deadline. Unconfirmed writes follow normal retry and loss policies; incident evaluation and receipt reconciliation use the normal storage path.

func (*Engine) Prune

func (e *Engine) Prune(ctx context.Context) (PruneResult, error)

Prune deletes expired telemetry under the shared storage lock. It is suitable for an app-owned maintenance task and never deletes application audit data.

func (*Engine) Reader

func (e *Engine) Reader() *Reader

Reader returns the engine's bounded read service. It shares Engine lifetime admission; requests after Close begins fail without touching the database.

func (*Engine) RecordBrowser

func (e *Engine) RecordBrowser(ctx context.Context, report BrowserError) error

RecordBrowser admits an untrusted browser report through the engine-owned collector. It preserves the collector's validation and bounded loss accounting; success is not a persistence receipt. Reports after Close begins count as shutdown loss and return nil without reopening intake or touching the database. Applications retain CSRF, body limits, rate limiting and portal authorization.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context) error

Run captures and persists periodically until cancellation or Close. Ordinary capture, storage and prune failures are counted and retried on later ticks; they do not terminate a foundation critical task. Final capture belongs to Close.

func (*Engine) RunID

func (e *Engine) RunID() model.ID[Run]

RunID returns this process's telemetry run identity, the same ID that its persisted run, buckets and receipts carry. Applications use it to bind process-local operations, such as log maintenance, to the current owner. An uninitialized engine returns the zero ID, which matches no run.

type Episode

type Episode uint64

Episode identifies a reopening of an incident.

type Event

type Event struct {
	ID        model.ID[Event]
	CreatedAt temporal.DateTime
	Detail    Detail
}

Event is an owned retained sample and the owner of public event UUIDs.

type EventQuery

type EventQuery struct {
	Fingerprint Fingerprint
	Page        orm.PageRequest
}

EventQuery selects retained samples for a canonical issue fingerprint.

type Fingerprint

type Fingerprint string

Fingerprint is a lowercase SHA-256 issue identity. Parse external values with ParseFingerprint; conversion from string alone does not validate it.

func ParseFingerprint

func ParseFingerprint(text string) (Fingerprint, error)

ParseFingerprint validates a canonical lowercase SHA-256 identity.

type Frame

type Frame struct {
	File, Function string
	Line, Column   int
}

Frame is a bounded source location without arguments, locals or error text.

type Health

type Health struct {
	Ready        value.Nullable[bool]
	State        foundation.State
	Mode         maintenance.Mode
	Dependencies []DependencyHealth
}

Health contains structural health only. An unset Ready means unavailable.

type Instance

type Instance string

Instance identifies a configured process instance, never an end user.

type Issue

type Issue struct {
	Fingerprint     Fingerprint
	Source          Source
	Code            string
	Route           http.RouteID
	Release         Release
	Count           int64
	FirstAt, LastAt temporal.DateTime
	Detail          Detail
}

Issue is an owned retained issue-group snapshot.

type IssueQuery

type IssueQuery struct {
	Source Source
	Page   orm.PageRequest
}

IssueQuery selects one source and a strictly bounded page.

type Overview

type Overview struct {
	Runs         []Run
	Alerts       []Alert
	OldestBucket value.Optional[temporal.DateTime]
	Truncated    bool
}

Overview contains owned retained snapshots. Truncated signals either list's limit.

type OverviewQuery

type OverviewQuery struct{ Window Window }

OverviewQuery selects the UI window; retained runs and incidents remain visible independently of it.

type Portal

type Portal string

Portal identifies an application-declared browser portal.

type PruneResult

type PruneResult struct {
	Metrics, Issues, Events, Receipts, Runs int64
}

PruneResult counts confirmed telemetry deletions, including metric and receipt rows removed by run cascades. An uncertain transaction returns no counts; a committed transaction can return counts together with a completion error.

type ReadLimits

type ReadLimits struct {
	MaxConcurrent, MaxOverviewRuns, MaxOverviewAlerts      int
	MaxTrafficRows, MaxTrafficGroups, MaxPage, MaxPageSize int
	Timeout                                                time.Duration
}

ReadLimits contains explicit positive admission, result, page and timeout bounds. Config.Validate also compares result limits with storage capacities.

func (ReadLimits) Validate

func (l ReadLimits) Validate() error

Validate requires positive read bounds and a representable page offset.

type Reader

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

Reader reads owned telemetry snapshots from the primary database. Calls enforce retention using PostgreSQL time, bounded concurrency, and the configured timeout. A full reader returns fault.Overloaded without queueing another database operation. The owning Engine closes admission; Reader never closes borrowed dependencies.

func (*Reader) Alerts

func (r *Reader) Alerts(ctx context.Context, q AlertQuery) (orm.PageResult[Alert], error)

Alerts returns a stable incident page whose owning runs remain within hour retention. An omitted state includes open, acknowledged and recovered episodes.

func (*Reader) Events

func (r *Reader) Events(ctx context.Context, q EventQuery) (orm.PageResult[Event], error)

Events returns retained samples for a fingerprint. Each sample's own source selects its retention, independent of whether its issue group still exists.

func (*Reader) Issue

func (r *Reader) Issue(ctx context.Context, fingerprint Fingerprint) (Issue, error)

Issue returns one retained issue by fingerprint, or database.NotFound when it is unknown or expired. It shares the primary read, timeout, concurrency and shutdown admission rules of Issues and returns an owned detail snapshot.

func (*Reader) Issues

func (r *Reader) Issues(ctx context.Context, q IssueQuery) (orm.PageResult[Issue], error)

Issues returns a stable page of one source, enforcing its configured retention even when the physical pruning job has not run.

func (*Reader) Overview

func (r *Reader) Overview(ctx context.Context, q OverviewQuery) (Overview, error)

Overview returns retained runs and incidents. Window is validated but does not narrow their retention; OldestBucket ignores already expired metric buckets.

func (*Reader) Traffic

func (r *Reader) Traffic(ctx context.Context, q TrafficQuery) (Traffic, error)

Traffic sums cumulative histogram buckets before estimating quantiles. Windows through sixty minutes use minute buckets; larger windows use hour buckets and include the partial starting bucket, subject to the server retention cutoff. Truncated results summarize only admitted rows and groups.

type Release

type Release string

Release identifies the deployed build accepting observations.

type RetentionPolicy

type RetentionPolicy struct {
	Minute, Hour, Issue, Security                                      time.Duration
	MaxRuns, MaxReceiptRows, MaxMetricRows, MaxIssueRows, MaxEventRows int
	PruneInterval                                                      time.Duration
}

RetentionPolicy bounds future storage and pruning. Minute/Security are one hour to seven days; Hour/Issue are at most thirty days. Hour must cover Minute. Row ranges are runs 100..10,000, metrics 100..1,000,000, issues 100..10,000 and events 100..100,000. Receipt capacity and prune interval must be positive.

func (RetentionPolicy) Validate

func (p RetentionPolicy) Validate() error

Validate checks retention durations, row capacities and prune timing.

type RoutePolicy

type RoutePolicy struct {
	ExcludedRoutes            []http.RouteID
	ExcludedPrefixes          []string
	ExcludedOperations        []observability.Name
	ExcludedOperationPrefixes []string
}

RoutePolicy excludes backend issues and identifies traffic excluded from later alert/read aggregation. HTTP metrics and security classification still run. Prefixes match declared identities, never raw request paths.

func (RoutePolicy) Validate

func (p RoutePolicy) Validate() error

Validate checks distinct bounded route/operation exclusions.

type Rule

type Rule string

Rule identifies a built-in incident rule; values do not enable evaluation.

const (
	RuleLatency             Rule = "latency"
	RuleHTTPErrors          Rule = "http_errors"
	RulePoolPressure        Rule = "pool_pressure"
	RuleLogFailures         Rule = "log_failures"
	RuleTelemetryLoss       Rule = "telemetry_loss"
	RuleAuthenticationBurst Rule = "authentication_burst"
)

func ParseRule

func ParseRule(text string) (Rule, error)

ParseRule decodes and validates an enum's text representation. Example: ParseRule(text)

func RuleValues

func RuleValues() []Rule

RuleValues returns declared values in source order, with independent slice ownership. Example: RuleValues()

func (Rule) EnumDescriptor

func (Rule) EnumDescriptor() enum.Descriptor[Rule]

EnumDescriptor describes this enum type independently of the receiver's value.

func (Rule) IsValid

func (v Rule) IsValid() bool

IsValid checks membership; a Go cast alone does not validate external values.

func (Rule) MarshalJSON

func (v Rule) MarshalJSON() ([]byte, error)

MarshalJSON encodes a validated enum as JSON.

func (Rule) MarshalText

func (v Rule) MarshalText() ([]byte, error)

MarshalText encodes a validated enum as text.

func (*Rule) Scan

func (v *Rule) Scan(source any) error

Scan changes the receiver only after successful decoding. SQL NULL is rejected.

func (*Rule) UnmarshalJSON

func (v *Rule) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes validated JSON and rejects null.

func (*Rule) UnmarshalText

func (v *Rule) UnmarshalText(data []byte) error

UnmarshalText decodes validated enum text and changes the receiver only on success.

func (Rule) Validate

func (v Rule) Validate() error

Validate reports invalid values without formatting the input.

func (Rule) Value

func (v Rule) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer through the shared typed codec.

type Run

type Run struct {
	ID                     model.ID[Run]
	Instance               Instance
	Release                Release
	StartedAt, HeartbeatAt temporal.DateTime
	Stale                  bool
	Runtime                Runtime
}

Run is an owned process observation snapshot and the owner of run UUIDs.

type Runtime

type Runtime struct {
	Health                   Health
	Samples                  []Sample
	Dropped, StorageFailures uint64
	Pending                  int
}

Runtime contains bounded samples and cumulative best-effort loss counters. Pending counts older retained batches at capture time. StorageFailures remains separate from admission loss; collection alone performs no storage operations.

type Sample

type Sample struct {
	Name, Labels string
	Value        float64
}

Sample is a recorder-owned metric copied at capture. Labels is the escaped Prometheus label representation, not markup or a payload channel.

type Source

type Source string

Source identifies the origin of an issue observation.

const (
	SourceBackend  Source = "backend"
	SourceBrowser  Source = "browser"
	SourceSecurity Source = "security"
)

func ParseSource

func ParseSource(text string) (Source, error)

ParseSource decodes and validates an enum's text representation. Example: ParseSource(text)

func SourceValues

func SourceValues() []Source

SourceValues returns declared values in source order, with independent slice ownership. Example: SourceValues()

func (Source) EnumDescriptor

func (Source) EnumDescriptor() enum.Descriptor[Source]

EnumDescriptor describes this enum type independently of the receiver's value.

func (Source) IsValid

func (v Source) IsValid() bool

IsValid checks membership; a Go cast alone does not validate external values.

func (Source) MarshalJSON

func (v Source) MarshalJSON() ([]byte, error)

MarshalJSON encodes a validated enum as JSON.

func (Source) MarshalText

func (v Source) MarshalText() ([]byte, error)

MarshalText encodes a validated enum as text.

func (*Source) Scan

func (v *Source) Scan(source any) error

Scan changes the receiver only after successful decoding. SQL NULL is rejected.

func (*Source) UnmarshalJSON

func (v *Source) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes validated JSON and rejects null.

func (*Source) UnmarshalText

func (v *Source) UnmarshalText(data []byte) error

UnmarshalText decodes validated enum text and changes the receiver only on success.

func (Source) Validate

func (v Source) Validate() error

Validate reports invalid values without formatting the input.

func (Source) Value

func (v Source) Value() (driver.Value, error)

Value implements database/sql/driver.Valuer through the shared typed codec.

type Thresholds

type Thresholds struct {
	Latency                       time.Duration
	ErrorRatio, PoolUsageRatio    float64
	MinimumRequests, AuthFailures int
}

Thresholds supplies explicit application choices. Ratios must be finite and in (0,1]; latency is in (0,60s], requests in 1..1,000,000 and auth failures in 1..4096.

func (Thresholds) Validate

func (t Thresholds) Validate() error

Validate checks every threshold without choosing application defaults.

type Traffic

type Traffic struct {
	Items     []TrafficRow
	Summary   TrafficSummary
	Truncated bool
}

Traffic contains owned rows. Truncated means a row or group limit omitted observations.

type TrafficQuery

type TrafficQuery struct {
	Window          Window
	IncludeExcluded bool
}

TrafficQuery selects aggregated traffic, optionally including excluded routes.

type TrafficRow

type TrafficRow struct {
	Route         http.RouteID
	RoutePath     string
	Method        http.Method
	Status        int
	Outcome       observability.Outcome
	Count         uint64
	Seconds       float64
	P50, P95, P99 observability.QuantileEstimate
}

TrafficRow aggregates compatible cumulative histograms across retained runs and buckets.

type TrafficSummary

type TrafficSummary struct {
	Count, Failed uint64
	P95           observability.QuantileEstimate
}

TrafficSummary describes the included groups; Failed counts HTTP statuses at least 500.

type Window

type Window struct{ Minutes int }

Window selects a bounded number of minutes. Applications may offer a narrower list.

func (Window) Validate

func (w Window) Validate() error

Validate rejects windows outside one minute through the maximum retention.

Directories

Path Synopsis
internal
store
Package store owns telemetry persistence declarations.
Package store owns telemetry persistence declarations.
Package sourcemap reads and prunes private, manifest-owned release artifacts.
Package sourcemap reads and prunes private, manifest-owned release artifacts.

Jump to

Keyboard shortcuts

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