Help us shape the future of Go! Take the 2026 Go Developer Survey

observability

package
v0.1.0-rc.41 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: BSD-3-Clause Imports: 59 Imported by: 0

Documentation

Overview

package observability owns tnl's OTel instruments, process-scoped metrics and trace providers, bounded optional OTLP/HTTPS export, and Prometheus exposition. observers report outcomes; control state remains the authorization authority.

Index

Constants

View Source
const CLIShutdownTimeout = 250 * time.Millisecond
View Source
const LaunchTraceparent = "TNL_TRACEPARENT"

LaunchTraceparent is a one-launch carrier, consumed before starting workers. it never belongs in a handle, project metadata, persisted job, or app payload.

View Source
const PortInventoryFreshness = 90 * time.Second
View Source
const ShutdownTimeout = 5 * time.Second

Variables

View Source
var (
	ServiceNamespace      = stringKey{keyName{"service.namespace"}}
	ServiceName           = stringKey{keyName{"service.name"}}
	ServiceVersion        = stringKey{keyName{"service.version"}}
	ServiceInstanceID     = stringKey{keyName{"service.instance.id"}}
	Environment           = stringKey{keyName{"deployment.environment.name"}}
	RoleKey               = metricEnumKey[Role]{keyName{"tnl.role"}}
	CloudProvider         = stringKey{keyName{"cloud.provider"}}
	CloudRegion           = stringKey{keyName{"cloud.region"}}
	CloudAvailabilityZone = stringKey{keyName{"cloud.availability_zone"}}
	TeamID                = metricStringKey{keyName{"tnl.team_id"}}
	DeploymentID          = metricStringKey{keyName{"tnl.deployment_id"}}
	ReplicaKey            = metricStringKey{keyName{"tnl.replica_key"}}
	PublisherGroupID      = metricStringKey{keyName{"tnl.publisher_group_id"}}
	PublisherIdentityID   = metricStringKey{keyName{"tnl.publisher_identity_id"}}
	ServiceID             = metricStringKey{keyName{"tnl.service_id"}}
	PublicURLID           = metricStringKey{keyName{"tnl.public_url_id"}}
	ServiceKindKey        = metricEnumKey[ServiceKind]{keyName{"tnl.service_kind"}}
	Component             = metricStringKey{keyName{"tnl.component"}}
	ServiceProtocol       = metricEnumKey[Protocol]{keyName{"tnl.service_protocol"}}
	KubernetesVerb        = stringKey{keyName{"tnl.kubernetes_verb"}}
	KubernetesAPIGroup    = stringKey{keyName{"tnl.kubernetes_api_group"}}
	KubernetesResource    = stringKey{keyName{"tnl.kubernetes_resource"}}
	KubernetesSubresource = stringKey{keyName{"tnl.kubernetes_subresource"}}
	Transport             = metricEnumKey[TransportValue]{keyName{"tnl.transport"}}
	TransportPreference   = metricEnumKey[TransportValue]{keyName{"tnl.transport_preference"}}
	AccessPath            = metricStringKey{keyName{"tnl.access_path"}}
	Exposure              = metricStringKey{keyName{"tnl.exposure"}}
	TLSLeg                = metricStringKey{keyName{"tnl.tls_leg"}}
	ConnectionSlot        = metricIntKey{keyName{"tnl.connection_slot"}}
	Direction             = metricStringKey{keyName{"tnl.direction"}}
	Operation             = metricEnumKey[operationName]{keyName{"tnl.operation"}}
	OutcomeKey            = metricEnumKey[Outcome]{keyName{"tnl.outcome"}}
	Reason                = metricStringKey{keyName{"tnl.reason"}}
	ErrorType             = stringKey{keyName{"error.type"}}
	State                 = metricEnumKey[LifecycleState]{keyName{"tnl.state"}}
	Event                 = metricEnumKey[LifecycleEvent]{keyName{"tnl.event"}}
	CertificateKind       = metricStringKey{keyName{"tnl.certificate_kind"}}
	DNSKind               = metricStringKey{keyName{"tnl.dns_kind"}}
	CleanupKind           = metricStringKey{keyName{"tnl.cleanup_kind"}}
	CapacityResource      = metricStringKey{keyName{"tnl.capacity_resource"}}
	HTTPMethod            = metricStringKey{keyName{"http.request.method"}}
	HTTPStatus            = metricIntKey{keyName{"http.response.status_code"}}
	HTTPRoute             = metricStringKey{keyName{"http.route"}}
	TLSVersion            = metricStringKey{keyName{"tls.protocol.version"}}
	TLSResumed            = metricBoolKey{keyName{"tls.resumed"}}
	ResponseOrigin        = metricStringKey{keyName{"tnl.response_origin"}}
	VisitorConnectionID   = stringKey{keyName{"tnl.visitor_connection_id"}}
	RequestID             = stringKey{keyName{"tnl.request_id"}}
	PublishRunID          = stringKey{keyName{"tnl.publish_run_id"}}
	PublishRunNumber      = intKey{keyName{"tnl.publish_run_number"}}
	PublisherConnectionID = stringKey{keyName{"tnl.publisher_connection_id"}}
	GrantID               = stringKey{keyName{"tnl.grant_id"}}
	ActorID               = stringKey{keyName{"tnl.actor_id"}}
	Revision              = intKey{keyName{"tnl.revision"}}
	ImageHash             = stringKey{keyName{"tnl.image_hash"}}
	MetricOverflow        = boolKey{keyName{"otel.metric.overflow"}}
	WorkloadSessionID     = stringKey{keyName{"tnl.workload_session_id"}}
	WorkloadRunID         = stringKey{keyName{"tnl.workload_run_id"}}
	WorkloadRunAttempt    = stringKey{keyName{"tnl.workload_run_attempt"}}
	WorkloadCheckRunID    = stringKey{keyName{"tnl.workload_check_run_id"}}
)

Functions

func Attributes

func Attributes(ctx context.Context, allowed ...MetricKey) []attribute.KeyValue

Attributes selects only metric-eligible scope fields for an explicit allowlist.

func AuthenticatedServerScope

func AuthenticatedServerScope(ctx context.Context, identity Identity, fields Fields) context.Context

AuthenticatedServerScope is called only after state has verified the exact credential. IDs and protocol stay on this span and explicitly scoped callers.

func AuthorizationAdmission

func AuthorizationAdmission(ctx context.Context, operation operationName, allowed, admitted bool)

AuthorizationAdmission distinguishes a valid credential from capacity/run admission. an allowed visitor that was not admitted is not an access denial.

func AuthorizationDecision

func AuthorizationDecision(ctx context.Context, operation operationName, allowed bool)

AuthorizationDecision records the semantic result separately from HTTP status. a valid HTTP 200 response may still deny access. operation is a compiled name.

func CertificateDNSKind

func CertificateDNSKind(ctx context.Context) string

func ClientCommand

func ClientCommand(ctx context.Context, command string) (context.Context, func(error))

ClientCommand accepts only compiled parser commands. serving commands measure startup, renewal, recovery and cleanup in their lifecycle owners instead.

func ClientLifecycle

func ClientLifecycle(ctx context.Context, event LifecycleEvent)

ClientLifecycle is called at the authoritative transition, not by status or watch readers. bound listeners are observed separately by the SDK that binds.

func ClientOperation

func ClientOperation(ctx context.Context, operation operationName, options ...trace.SpanStartOption) (context.Context, func(error))

ClientOperation measures one finite client-owned boundary exactly once.

func ControlOperation

func ControlOperation(ctx context.Context, operation string) (context.Context, func(error))

ControlOperation starts before database work so driver spans inherit the operation, rather than constructing a disconnected span after completion.

func Correlation

func Correlation(ctx context.Context) string

Correlation returns only OTel trace identifiers for existing one-line logs. it does not format request input or copy arbitrary context values.

func DialTarget

func DialTarget(ctx context.Context, network, address string) (net.Conn, error)

DialTarget observes the connection boundary without recording the address or sending trace headers to the customer's target.

func DrainingRequest

func DrainingRequest(ctx context.Context)

DrainingRequest marks an intentional process admission rejection, even when its retryable HTTP response is 503. it is not an infrastructure failure.

func DurationBucketsSeconds

func DurationBucketsSeconds() []float64

DurationBucketsSeconds returns independent boundaries shared by operation, HTTP, SQL, and driver-observed guard histograms. the final implicit +Inf bucket also counts operations longer than two minutes.

func ExtractLaunch

func ExtractLaunch(ctx context.Context, parent string) context.Context

func ExtractWireTrace

func ExtractWireTrace(ctx context.Context, tc tunnelv1.TraceContext) context.Context

ExtractWireTrace replaces only span parentage, retaining the receiver's local identity and instruments. remote sampling is untrusted: the parent is marked remote with its sampled flag cleared; the receiver's remote-parent sampler must use local policy. an empty or malformed parent clears any pooled session's span to prevent leaks.

func FailureCode

func FailureCode(err error) string

FailureCode exports only codes owned by the failure or diagnostic catalog.

func Independent

func Independent(ctx context.Context) context.Context

Independent keeps local ownership and cancellation, but later attempts are roots linked to the scheduling operation, never its indefinitely held child.

func InjectLocalTrace

func InjectLocalTrace(ctx context.Context, header http.Header)

InjectLocalTrace sends a canonical parent only, even without an exporter.

func LaunchEnvironment

func LaunchEnvironment(ctx context.Context, environment []string) []string

func LinkContext

func LinkContext(owner, scheduling context.Context) context.Context

LinkContext keeps the worker owner's values and cancellation. only scheduling IDs cross from the request; request identity and lifetime never become state.

func LocalRequests

func LocalRequests(next http.Handler) http.Handler

LocalRequests traces only the private native IPC routes. no supplied path, capability, request body, or project name enters the observation.

func MarkReason

func MarkReason(ctx context.Context, reason string)

MarkReason accepts only closed domain classifications, never cause text.

func NarrowIdentity

func NarrowIdentity(ctx context.Context, id Identity) context.Context

NarrowIdentity keeps parent deployment/group scope only within the same team and publisher. service scope is always replaced (or cleared). a changed team, publisher, group, or deployment starts a new scope instead of inheriting it.

func ObservePublisherRuntime

func ObservePublisherRuntime(ctx context.Context, action, result string, elapsed time.Duration)

func OperationalFailure

func OperationalFailure(ctx context.Context, operation failure.Operation, reason failure.Reason, requestID string, cause error)

OperationalFailure exports authored failure copy with scoped identity and trace correlation. it never accepts a free-form log body or exports cause.Error().

func OwnedHTTPClient

func OwnedHTTPClient(client *http.Client, surface string) *http.Client

OwnedHTTPClient must only wrap a client dedicated to tnl-owned HTTP APIs. customer target clients and DNS/CA/identity-provider clients never use it. no URL, path, header, body or peer address becomes an attribute.

func ParseMetrics

func ParseMetrics(reader io.Reader) ([]*dto.MetricFamily, error)

ParseMetrics decodes Prometheus text exposition, retaining types and labels.

func ProcessHandler

func ProcessHandler(metrics http.Handler, ready func() bool) http.Handler

ProcessHandler serves private process health, readiness, and metrics.

func PublisherAuthorization

func PublisherAuthorization(ctx context.Context, allowed, admitted bool, err error)

PublisherAuthorization records each authority result, including allowed checks still waiting for admission. errors retain their owned classification.

func PublisherConnection

func PublisherConnection(ctx context.Context, transport string, preferTCP bool, err error)

func PublisherConnectionLifetime

func PublisherConnectionLifetime(ctx context.Context, transport string, slot int) func(error, bool)

PublisherConnectionLifetime observes authenticated connections, including replacements. a shutdown close remains expected even if the transport errs.

func PublisherHTTP

func PublisherHTTP(next http.Handler) http.Handler

PublisherHTTP observes the whole handler independently of inspection settings. no propagation headers are injected into customer requests.

func PublisherHTTPError

func PublisherHTTPError(ctx context.Context, err error)

func PublisherHTTPForward

func PublisherHTTPForward(ctx context.Context)

PublisherHTTPForward marks the proxy's target boundary after request admission. publisher-owned handlers do not contribute forwarded application body bytes.

func PublisherHTTPResponse

func PublisherHTTPResponse(ctx context.Context)

PublisherHTTPResponse is called only after the proxy accepts a target response.

func PublisherHTTPUpgrade

func PublisherHTTPUpgrade(response *http.Response)

PublisherHTTPUpgrade observes backend copy failures without hiding the ReadWriteCloser required by ReverseProxy or its optional write-half close. bytes are counted at the visitor socket, exactly once.

func PublisherHTTPWriteError

func PublisherHTTPWriteError(ctx context.Context, err error)

func PublisherLease

func PublisherLease(ctx context.Context, expires time.Time)

func PublisherOperation

func PublisherOperation(ctx context.Context, operation operationName) (context.Context, func(error))

PublisherOperation includes the scoped, authenticated identities in metrics. these spans end at the operation boundary, not when the publisher exits.

func PublisherReadiness

func PublisherReadiness(ctx context.Context, ready bool)

func PublisherReadinessStatus

func PublisherReadinessStatus(ctx context.Context, ready, healthy, current bool, checked, succeeded time.Time)

PublisherReadinessStatus records a snapshot, not a lifecycle callback. the caller retains last success across failures and never extends a failed lease.

func PublisherStream

func PublisherStream(ctx context.Context, target net.Conn) (net.Conn, func(error))

PublisherStream wraps only application copy after native authentication. reads on the target are target-to-visitor and writes are visitor-to-target.

func PublisherTLS

func PublisherTLS(ctx context.Context, leg string, state tls.ConnectionState, err error)

PublisherTLS records negotiated facts without peer names or certificates.

func PublisherTransportCandidate

func PublisherTransportCandidate(ctx context.Context, transport string, elapsed time.Duration, err error)

PublisherTransportCandidate records each bounded candidate independently of the race winner. connector/client owners retain spans but not publisher metrics.

func ReplaceIdentity

func ReplaceIdentity(ctx context.Context, id Identity) context.Context

ReplaceIdentity replaces every field, including empty fields. use this at an authentication boundary, especially when a context may belong to another team.

func ResponseContext

func ResponseContext(w http.ResponseWriter) context.Context

ResponseContext lets existing problem adapters retain request correlation without retaining requests or changing every authored problem's signature.

func Start

func Start(ctx context.Context, name operationName, options ...trace.SpanStartOption) (context.Context, func(error))

Start records a finite, authored operation. callers must not pass paths, hostnames, errors or other external input as the name. errors become a fixed outcome; raw causes are never recorded as span status or exception events.

func TLSAttributes

func TLSAttributes(state tls.ConnectionState) []attribute.KeyValue

TLSAttributes accepts negotiated state, never certificate subjects or peers.

func TargetDiscovery

func TargetDiscovery(ctx context.Context, kind, protocol, result string, duration time.Duration)

TargetDiscovery accepts only compiled low-cardinality classes. selectors, ARNs, resource IDs, hosts, regions and SDK response text are never dimensions.

func TargetDiscoveryCache

func TargetDiscoveryCache(ctx context.Context, kind, protocol, state string, success time.Time)

func TargetDiscoveryIdentity

func TargetDiscoveryIdentity(ctx context.Context, arn, resourceID string)

TargetDiscoveryIdentity is trace-only correlation for validated metadata. selectors, network endpoints and provider response bodies are excluded.

func TargetRequest

func TargetRequest(request *http.Request) *http.Request

TargetRequest observes the standard transport's TLS handshake locally. it never extracts or injects propagation headers on customer HTTP requests.

func Visitor

func Visitor(ctx context.Context, id string)

Visitor correlates independent tunnel-hop spans without adding fields to the tunnel protocol or treating an external ID as an OTel parent span.

func WireTrace

func WireTrace(ctx context.Context) tunnelv1.TraceContext

WireTrace exports only the current span's bounded W3C parent. process identity, tenant fields, tracestate, and baggage never cross this telemetry boundary.

func WithCertificateKind

func WithCertificateKind(ctx context.Context, kind string) context.Context

func WithFields

func WithFields(ctx context.Context, fields Fields) context.Context

func WithMetrics

func WithMetrics(ctx context.Context, m *Metrics) context.Context

func WithPublisherProtocol

func WithPublisherProtocol(ctx context.Context, protocol string) context.Context

WithPublisherProtocol adds known publisher protocol scope without clearing the caller's access path, exposure, connection slot, or other bounded fields.

func WithPublisherRecovery

func WithPublisherRecovery(ctx context.Context) context.Context

WithPublisherRecovery creates one service/run-local recovery observer. share the resulting context with its connection slots and visitor handlers only.

func WithPublisherRecoveryFrom

func WithPublisherRecoveryFrom(ctx, owner context.Context) context.Context

WithPublisherRecoveryFrom shares only the run-local recovery observer. it preserves the receiving context's cancellation, identity, fields and spans. a source without an observer clears any previous run's recovery scope.

func WithVisitor

func WithVisitor(ctx context.Context, id string) context.Context

func WorkerAttempt

func WorkerAttempt(ctx context.Context, operation operationName) (context.Context, func(error))

WorkerAttempt is finite asynchronous work. link a scheduling span when one exists without pretending a later worker iteration is part of that request. no scheduling context, SQL, work payload, or errors are retained between runs.

func WorkloadExecution

func WorkloadExecution(ctx context.Context, session, run, attempt, check string)

WorkloadExecution attaches only control-authenticated execution references. these fields are trace-only, never metric dimensions or visitor baggage.

Types

type APIRequestOutcome

type APIRequestOutcome string
const (
	APIRequestSuccess          APIRequestOutcome = "success"
	APIRequestDeadlineExceeded APIRequestOutcome = "deadline_exceeded"
	APIRequestCanceled         APIRequestOutcome = "canceled"
	APIRequestServerError      APIRequestOutcome = "server_error"
	APIRequestClientError      APIRequestOutcome = "client_error"
	APIRequestDenied           APIRequestOutcome = "denied"
	APIRequestNotAdmitted      APIRequestOutcome = "not_admitted"
	APIRequestDraining         APIRequestOutcome = "draining"
)

type AttributeDefinition

type AttributeDefinition struct {
	Key             Key             `json:"key"`
	Values          []string        `json:"values,omitempty"`
	Semantics       string          `json:"semantics"`
	DimensionPolicy DimensionPolicy `json:"dimension_policy"`
	ValueType       string          `json:"value_type,omitempty"`
}

func VocabularyAttributes

func VocabularyAttributes() []AttributeDefinition

VocabularyAttributes is the shared key/value/semantics/dimension policy model.

type CertificateClaimOutcome

type CertificateClaimOutcome string
const (
	CertificateClaimed CertificateClaimOutcome = "claimed"
	CertificateEmpty   CertificateClaimOutcome = "empty"
	CertificateError   CertificateClaimOutcome = "error"
)

type CertificateWorkOutcome

type CertificateWorkOutcome string
const (
	CertificateProgress   CertificateWorkOutcome = "progress"
	CertificateRetry      CertificateWorkOutcome = "retry"
	CertificateTerminal   CertificateWorkOutcome = "terminal"
	CertificateSaveFailed CertificateWorkOutcome = "save_failed"
)

type Config

type Config struct {
	Metrics, Traces, Logs      SignalConfig
	ServiceName                string
	Resource                   []attribute.KeyValue
	Interval                   time.Duration
	QueueSize, BatchSize       int
	BatchDelay                 time.Duration
	LogQueueSize, LogBatchSize int
	LogBatchDelay              time.Duration
	SampleRatio                float64
	Sampler                    string
	Disabled                   bool
}

Config contains only export settings. no endpoint means no network export. resource attributes are fixed process facts, never a current request's tenant.

func ConfigFromEnv

func ConfigFromEnv(getenv func(string) string) (Config, error)

ConfigFromEnv accepts the standard OTLP/HTTP configuration subset documented in metrics.md. errors include only the setting name, never its input value.

func (Config) GoString

func (Config) GoString() string

func (Config) String

func (Config) String() string

type DNSWorkOutcome

type DNSWorkOutcome string
const (
	DNSWorkSuccess DNSWorkOutcome = "success"
	DNSWorkPending DNSWorkOutcome = "pending"
	DNSWorkError   DNSWorkOutcome = "error"
)

type DatabaseConnectionSnapshot

type DatabaseConnectionSnapshot struct {
	Open       int64
	Connecting int64
	Opened     int64
	Closed     int64
	Failed     int64
}

type DatabaseOperationCatalog

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

func DatabaseOperations

func DatabaseOperations(sources embed.FS) DatabaseOperationCatalog

DatabaseOperations reads sqlc declarations embedded in the caller's binary. accepting embed.FS rather than fs.FS keeps runtime files and supplied strings out of this authoring boundary. Lookup validates driver names against it.

func (DatabaseOperationCatalog) Contains

func (c DatabaseOperationCatalog) Contains(name string) bool

func (DatabaseOperationCatalog) Lookup

Lookup never retains an unknown input, even when it resembles a query name.

type DatabaseOperationName

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

DatabaseOperationName can only come from a compiled SQL source catalog. it carries the name alone, never SQL, arguments, or a backing provider buffer.

func (DatabaseOperationName) String

func (v DatabaseOperationName) String() string

type DatabaseOperationSnapshot

type DatabaseOperationSnapshot struct {
	Operation      DatabaseOperationName
	ElapsedSeconds float64
}

type DatabaseSnapshot

type DatabaseSnapshot struct {
	Pool              *pgxpool.Stat
	Connections       map[string]DatabaseConnectionSnapshot
	ActiveOperations  []DatabaseOperationSnapshot
	OperationsOmitted int
}

DatabaseSnapshot is process-local database state collected without I/O.

type Dimension

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

Dimension is a named metric value. its private representation prevents an OTel attribute (including a trace-only identifier) from entering a metric binding.

type DimensionPolicy

type DimensionPolicy uint8

DimensionPolicy describes where a declared attribute may be exported.

const (
	PolicyResource DimensionPolicy = iota + 1
	PolicyScoped
	PolicyBounded
	PolicyTraceLog
	PolicySDK
)

func (DimensionPolicy) MarshalJSON

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

func (DimensionPolicy) String

func (v DimensionPolicy) String() string

type DurationSummary

type DurationSummary struct {
	Name        string            `json:"name"`
	Labels      map[string]string `json:"labels"`
	Count       uint64            `json:"count"`
	SumSeconds  float64           `json:"sum_seconds"`
	MeanSeconds float64           `json:"mean_seconds"`
	P50Seconds  *float64          `json:"p50_seconds"`
	P95Seconds  *float64          `json:"p95_seconds"`
	P99Seconds  *float64          `json:"p99_seconds"`
}

DurationSummary describes observations between two process-local snapshots. quantiles are linear estimates within classic histogram buckets, not exact samples or maxima. they are nil for an empty interval or the unbounded bucket.

func DurationSummaries

func DurationSummaries(before, after []*dto.MetricFamily) ([]DurationSummary, error)

DurationSummaries differences classic histogram counts, sums, and cumulative buckets before estimating quantiles. inputs must describe the same process; process_start_time_seconds and histogram creation timestamps, when present, also detect restarts. new lazy series start at zero. missing end series, changed layouts, invalid samples, and detectable resets invalidate the interval. only histogram names ending in _seconds are durations. SDK queue/batch size histograms and future byte distributions must not be interpreted as time.

type Fields

type Fields struct {
	Component           string
	ServiceProtocol     Protocol
	Transport           TransportValue
	TransportPreference TransportValue
	AccessPath          string
	Exposure            string
	TLSLeg              string
	Direction           string
	ConnectionSlot      *int
	ResponseOrigin      string
}

Fields replaces protocol/component scope. protocol and transport must be parsed at external boundaries; unspecified or invalid values are omitted.

type Identity

type Identity struct {
	TeamID, PublisherGroupID, PublisherIdentityID, DeploymentID, ReplicaKey string
	ServiceID, PublicURLID                                                  string
	ServiceKind                                                             ServiceKind
}

Identity contains authenticated stable scope, not request-supplied identifiers. the public URL and service slots are mutually exclusive. a conflicting or invalid identity is cleared rather than attributed to the previous tenant.

func IdentityFromContext

func IdentityFromContext(ctx context.Context) Identity

type IngressRoutingSnapshot

type IngressRoutingSnapshot struct {
	Initialized          bool
	CaughtUp             bool
	LastSuccessfulCheck  time.Time
	LastCaughtUp         time.Time
	LastAcknowledged     time.Time
	LatestRevision       int64
	AppliedRevision      int64
	AcknowledgedRevision int64
	UpdateFailures       uint64
	Resnapshots          uint64
}

IngressRoutingSnapshot is bounded, process-local controller state. revisions describe successful routing responses, not control's current revision while a request is pending. CaughtUp requires an event response confirming catch-up; applying the initial snapshot alone only establishes Initialized.

type InstrumentDefinition

type InstrumentDefinition struct {
	Name           string         `json:"name"`
	Semantics      string         `json:"semantics"`
	Kind           InstrumentKind `json:"kind"`
	Dimensions     []Key          `json:"dimensions"`
	ExplicitBounds []float64      `json:"explicit_bounds,omitempty"`
}

InstrumentDefinition is generated from the actual instrument declarations. dimensions are an allowlist, not labels automatically attached to every point.

func RuntimeInstrumentDefinitions

func RuntimeInstrumentDefinitions() []InstrumentDefinition

RuntimeInstrumentDefinitions names the supported subset of the pinned Prometheus Go/process bridge, using actual OTLP names and data types. summary is an OTLP summary, not an explicit-bucket histogram. process metrics can be absent on platforms where their collector is unavailable. no prefix wildcard admits newly introduced runtime metrics into the hosted contract.

type InstrumentKind

type InstrumentKind uint8

InstrumentKind preserves the wire spelling while separating instrument kinds from descriptions, dimension policies, and arbitrary strings.

const (
	KindCounter InstrumentKind = iota + 1
	KindGauge
	KindHistogram
	KindSummary
)

func (InstrumentKind) MarshalJSON

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

func (InstrumentKind) String

func (v InstrumentKind) String() string

type Key

type Key string

Key is a catalog name, not an attribute constructor. the private handle representation also prevents changing an inferred handle's name with a literal.

type LifecycleEvent

type LifecycleEvent uint8
const (
	EventQueued LifecycleEvent = iota + 1
	EventDelivered
	EventRetry
	EventDropped
	EventAccepted
	EventDuplicate
	EventConnected
	EventExpectedClose
	EventUnexpectedClose
	EventOperationalFailure
	EventIncomplete
	EventFinalized
	EventRetried
	EventRejected
	EventIssued
	EventAllocated
	EventReady
	EventExpired
	EventReadyLimit
	EventTransferLimit
	EventCleanup
	EventOpened
	EventClosed
	EventFailed
	EventBound
	EventRegistered
	EventPublicationReady
	EventBusy
	EventCompleted
	EventPartialFailed
)

func ParseEvent

func ParseEvent(value string) (LifecycleEvent, bool)

func (LifecycleEvent) String

func (v LifecycleEvent) String() string

type LifecycleState

type LifecycleState uint8
const (
	StateReady LifecycleState = iota + 1
	StateNotReady
	StateActive
	StateDraining
	StateFresh
	StateLastSuccess
	StateStale
	StateFailed
	StateDenied
	StateAdmitted
	StatePending
	StateAvailable
	StateInstalled
	StateCleanupComplete
	StatePublished
	StateRemoved
	StateReleased
	StateConfigured
	StateClaimed
	StateQuarantined
	StateOpen
	StateConnecting
	StateCertificateMissing
	StateConnectionsMissing
	StateCertificateAndConnectionsMissing
	StateDNSPending
	StateDNSFailed
	StateError
)

func ParseState

func ParseState(value string) (LifecycleState, bool)

func (LifecycleState) String

func (v LifecycleState) String() string

type MetricKey

type MetricKey interface {
	// contains filtered or unexported methods
}

MetricKey is sealed: resource-only, SDK, and trace/log-only handles do not implement it.

type Metrics

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

Metrics owns one process's OTel instruments, providers, and scrape exporter.

func FromContext

func FromContext(ctx context.Context) *Metrics

func New

func New(role string) *Metrics

New constructs an isolated, local-only owner. it never reads export settings.

func StartProcess

func StartProcess(ctx context.Context, role string) (context.Context, *Metrics, error)

StartProcess is called once by the native process entry point. child workers inherit its context; they do not create providers or read export settings.

func (*Metrics) APIRequests

func (m *Metrics) APIRequests(surface string, next http.Handler) http.Handler

APIRequests records matched route patterns, never URLs or resource IDs. wrap the router so authentication and parameter-binding failures are counted too.

func (*Metrics) AddAssignmentReplacements

func (m *Metrics) AddAssignmentReplacements(reason string, count int)

func (*Metrics) AddForwardedBytes

func (m *Metrics) AddForwardedBytes(direction string, count int64)

func (*Metrics) AddReadyPublisherConnections

func (m *Metrics) AddReadyPublisherConnections(delta int)

func (*Metrics) AddRecoveryPending

func (m *Metrics) AddRecoveryPending(delta int)

func (*Metrics) AddRegisteredPublisherConnections

func (m *Metrics) AddRegisteredPublisherConnections(delta int)

func (*Metrics) AddRelayLeases

func (m *Metrics) AddRelayLeases(state string, delta int)

func (*Metrics) AddRelayStreams

func (m *Metrics) AddRelayStreams(delta int)

func (*Metrics) AddUsageItems

func (m *Metrics) AddUsageItems(result string, count int)

func (*Metrics) ForceFlush

func (m *Metrics) ForceFlush(ctx context.Context) error

func (*Metrics) Gather

func (m *Metrics) Gather() ([]*dto.MetricFamily, error)

Gather captures this process's registry using only passive collectors.

func (*Metrics) Handler

func (m *Metrics) Handler() http.Handler

func (*Metrics) IncCapacityRejection

func (m *Metrics) IncCapacityRejection(resource string)

func (*Metrics) IncDrainingRejection

func (m *Metrics) IncDrainingRejection()

func (*Metrics) IncInspectionFailure

func (m *Metrics) IncInspectionFailure(stage string)

func (*Metrics) InstrumentDefinitions

func (m *Metrics) InstrumentDefinitions() []InstrumentDefinition

InstrumentDefinitions returns a detached, sorted snapshot for documentation.

func (*Metrics) ObserveAPIRequest

func (m *Metrics) ObserveAPIRequest(surface, operation string, outcome APIRequestOutcome, duration time.Duration)

func (*Metrics) ObserveCertificateClaim

func (m *Metrics) ObserveCertificateClaim(kind string, outcome CertificateClaimOutcome)

func (*Metrics) ObserveCertificateIteration

func (m *Metrics) ObserveCertificateIteration(kind, stage string, outcome CertificateWorkOutcome, duration time.Duration)

func (*Metrics) ObserveCertificateIterationContext

func (m *Metrics) ObserveCertificateIterationContext(ctx context.Context, kind, stage string, outcome CertificateWorkOutcome, duration time.Duration)

func (*Metrics) ObserveCertificateMilestone

func (m *Metrics) ObserveCertificateMilestone(kind, milestone string, age time.Duration)

func (*Metrics) ObserveCertificateOrder

func (m *Metrics) ObserveCertificateOrder(kind, domain, plan string)

func (*Metrics) ObserveCertificateTransition

func (m *Metrics) ObserveCertificateTransition(kind, state string)

func (*Metrics) ObserveCertificateWork

func (m *Metrics) ObserveCertificateWork(stage string, outcome CertificateWorkOutcome, duration time.Duration)

func (*Metrics) ObserveCleanup

func (m *Metrics) ObserveCleanup(kind string, count int, busy bool, err error)

func (*Metrics) ObserveDNSTransition

func (m *Metrics) ObserveDNSTransition(kind, state string)

func (*Metrics) ObserveDNSWork

func (m *Metrics) ObserveDNSWork(kind, phase string, outcome DNSWorkOutcome, elapsed time.Duration)

func (*Metrics) ObserveDNSWorkContext

func (m *Metrics) ObserveDNSWorkContext(ctx context.Context, kind, phase string, outcome DNSWorkOutcome, elapsed time.Duration)

func (*Metrics) ObserveDatabaseAcquire

func (m *Metrics) ObserveDatabaseAcquire(err error, elapsed time.Duration)

func (*Metrics) ObserveDatabaseAcquireContext

func (m *Metrics) ObserveDatabaseAcquireContext(ctx context.Context, err error, elapsed time.Duration)

func (*Metrics) ObserveDatabaseGuard

func (m *Metrics) ObserveDatabaseGuard(operation DatabaseOperationName, err error, elapsed time.Duration)

ObserveDatabaseGuard records a driver-observed guard interval. outcome is the transaction-ending command's outcome, not the application operation's outcome.

func (*Metrics) ObserveDatabaseGuardContext

func (m *Metrics) ObserveDatabaseGuardContext(ctx context.Context, operation DatabaseOperationName, err error, elapsed time.Duration)

func (*Metrics) ObserveDatabaseQuery

func (m *Metrics) ObserveDatabaseQuery(operation DatabaseOperationName, err error, elapsed time.Duration)

ObserveDatabaseQuery accepts only names sanitized by the controlstate tracer: compiled sqlc operations, transaction commands, or the fixed "unknown" label.

func (*Metrics) ObserveDatabaseQueryContext

func (m *Metrics) ObserveDatabaseQueryContext(ctx context.Context, operation DatabaseOperationName, err error, elapsed time.Duration)

func (*Metrics) ObserveOperation

func (m *Metrics) ObserveOperation(operation string, err error, elapsed time.Duration)

ObserveOperation records only the fixed application operations below. nil metrics are useful for callers that do not run a process metrics listener.

func (*Metrics) ObserveOperationContext

func (m *Metrics) ObserveOperationContext(ctx context.Context, operation string, err error, elapsed time.Duration)

ObserveOperationContext attaches a measured interval to the caller's span and metric exemplar context. use it instead of adding a second span at this boundary.

func (*Metrics) ObservePlacement

func (m *Metrics) ObservePlacement(action string, outcome PlacementOutcome)

func (*Metrics) ObservePublicURLCreated

func (m *Metrics) ObservePublicURLCreated(purpose string)

func (*Metrics) ObservePublishRunReadiness

func (m *Metrics) ObservePublishRunReadiness(outcome readiness.Outcome, duration, age time.Duration)

outcomes and stages are closed sets, independent of public URL and order identity.

func (*Metrics) ObservePublishRunReady

func (m *Metrics) ObservePublishRunReady(purpose string)

func (*Metrics) ObservePublisherExit

func (m *Metrics) ObservePublisherExit(unexpected bool)

func (*Metrics) ObserveRecoveryAttempt

func (m *Metrics) ObserveRecoveryAttempt(outcome RecoveryAttemptOutcome)

func (*Metrics) ObserveRecoveryDuration

func (m *Metrics) ObserveRecoveryDuration(duration time.Duration)

func (*Metrics) ObserveRelayAttempt

func (m *Metrics) ObserveRelayAttempt(slot string, outcome RelayAttemptOutcome)

func (*Metrics) ObserveRelayStreamRejection

func (m *Metrics) ObserveRelayStreamRejection(reason string)

func (*Metrics) ObserveRelayTransfer

func (m *Metrics) ObserveRelayTransfer(kind string, toPublisher, toVisitor int64, err error)

func (*Metrics) ObserveRoutingHistoryBatch

func (m *Metrics) ObserveRoutingHistoryBatch(scanned, deleted int64, busy bool)

func (*Metrics) ObserveRoutingHistoryFloor

func (m *Metrics) ObserveRoutingHistoryFloor(revision uint64)

func (*Metrics) ObserveTrafficAdmission

func (m *Metrics) ObserveTrafficAdmission(stage, result string)

func (*Metrics) ObserveUsageReceiver

func (m *Metrics) ObserveUsageReceiver(outcome UsageReceiverOutcome, elapsed time.Duration)

func (*Metrics) ObserveUsageWork

func (m *Metrics) ObserveUsageWork(phase string, outcome UsageWorkOutcome)

func (*Metrics) ObserveVisitor

func (m *Metrics) ObserveVisitor(outcome VisitorOutcome)

visitor outcomes describe the last ingress boundary reached, not a completed TLS handshake or a successful HTTP request at the local service.

func (*Metrics) ObserveVisitorOpen

func (m *Metrics) ObserveVisitorOpen(success bool, elapsed time.Duration)

func (*Metrics) ObserveWebhookProviderSource

func (m *Metrics) ObserveWebhookProviderSource(provider, outcome string)

ObserveWebhookProviderSource counts catalog lookups without URL or identity labels.

func (*Metrics) RegisterControlCertificate

func (m *Metrics) RegisterControlCertificate(source func() time.Time)

RegisterControlCertificate reads certificate material already in this process.

func (*Metrics) RegisterDatabase

func (m *Metrics) RegisterDatabase(source func(time.Time) DatabaseSnapshot)

RegisterDatabase exposes in-memory database state. its source must never acquire a connection because collection must remain available under database contention and pool exhaustion.

func (*Metrics) RegisterIngressLease

func (m *Metrics) RegisterIngressLease(source func() time.Time)

RegisterIngressLease reads a local controller snapshot without external I/O.

func (*Metrics) RegisterIngressRouting

func (m *Metrics) RegisterIngressRouting(source func() IngressRoutingSnapshot)

RegisterIngressRouting exposes one ingress controller's in-memory state. the source must perform no network or database I/O, including during a stalled poll.

func (*Metrics) ReplacePortPoolCapacity

func (m *Metrics) ReplacePortPoolCapacity(pools []PortPoolCapacity, refreshed time.Time)

ReplacePortPoolCapacity publishes one successful, complete database snapshot. failures retain its timestamp, never renew its freshness or partially replace it.

func (*Metrics) ServiceAuditCount

func (m *Metrics) ServiceAuditCount(result string, n uint64)

ServiceAuditCount accepts fixed outcomes only; IDs, IPs and errors are never metric labels. dropped includes overflow, invalid input and shutdown loss.

func (*Metrics) SetCapacityLimit

func (m *Metrics) SetCapacityLimit(resource string, limit int64)

func (*Metrics) SetGuestTrialStats

func (m *Metrics) SetGuestTrialStats(issued, allocated, ready, expired, readyLimit, transferLimit int64)

SetGuestTrialStats observes committed service-wide counts without identity labels.

func (*Metrics) SetIngressConnections

func (m *Metrics) SetIngressConnections(class string, count int)

func (*Metrics) SetIngressStreams

func (m *Metrics) SetIngressStreams(count int)

func (*Metrics) SetReadyPublisherConnections

func (m *Metrics) SetReadyPublisherConnections(count int)

func (*Metrics) SetRelayCertificateExpiry

func (m *Metrics) SetRelayCertificateExpiry(identity string, expires time.Time)

func (*Metrics) SetRelayLeaseExpiry

func (m *Metrics) SetRelayLeaseExpiry(identity string, expires time.Time)

func (*Metrics) SetRelayLeases

func (m *Metrics) SetRelayLeases(state string, count int)

func (*Metrics) SetUsageRetained

func (m *Metrics) SetUsageRetained(count int)

func (*Metrics) Shutdown

func (m *Metrics) Shutdown(ctx context.Context) error

Shutdown has one shared deadline, independent of the canceled traffic context. callers invoke it after draining workers; export errors never become traffic errors. the providers themselves make repeated shutdown harmless.

type Outcome

type Outcome uint8
const (
	Success Outcome = iota + 1
	Denied
	Rejected
	Timeout
	Canceled
	Error
)

func ErrorOutcome

func ErrorOutcome(err error) Outcome

ErrorOutcome classifies causes without formatting them. callers retain the original error; this function never wraps or replaces it.

func (Outcome) String

func (v Outcome) String() string

type PlacementOutcome

type PlacementOutcome string
const (
	PlacementPlaced               PlacementOutcome = "placed"
	PlacementInsufficientServices PlacementOutcome = "insufficient_services"
	PlacementCapacity             PlacementOutcome = "capacity"
	PlacementUnavailable          PlacementOutcome = "unavailable"
	PlacementStale                PlacementOutcome = "stale"
	PlacementError                PlacementOutcome = "error"
)

type PortPoolCapacity

type PortPoolCapacity struct {
	Pool                                        string
	Configured, Claimed, Quarantined, Available int64
}

type Protocol

type Protocol uint8

these ordinal types cannot be narrowed from a string by a cast. parsers omit unknown external values; zero is always unspecified, never an invented value.

const (
	ProtocolHTTP Protocol = iota + 1
	ProtocolPostgres
	ProtocolMySQL
	ProtocolTCP
	ProtocolKubernetes
)

func ParseProtocol

func ParseProtocol(value string) (Protocol, bool)

func (Protocol) String

func (v Protocol) String() string

type RecoveryAttemptOutcome

type RecoveryAttemptOutcome string
const (
	RecoveryAttemptSuccess  RecoveryAttemptOutcome = "success"
	RecoveryAttemptStale    RecoveryAttemptOutcome = "stale"
	RecoveryAttemptRetry    RecoveryAttemptOutcome = "retry"
	RecoveryAttemptCanceled RecoveryAttemptOutcome = "canceled"
)

type RelayAttemptOutcome

type RelayAttemptOutcome string
const (
	RelayAttemptOpenFailed      RelayAttemptOutcome = "open_failed"
	RelayAttemptSetupFailed     RelayAttemptOutcome = "setup_failed"
	RelayAttemptCommittedFailed RelayAttemptOutcome = "committed_failed"
	RelayAttemptCommitted       RelayAttemptOutcome = "committed"
	RelayAttemptOther           RelayAttemptOutcome = "other"
)

type Role

type Role uint8
const (
	RoleControl Role = iota + 1
	RoleIngress
	RoleRelay
	RoleStandalone
	RolePublisher
	RoleClient
	RoleAccounts
	RoleCollector
)

func ParseRole

func ParseRole(value string) (Role, bool)

func (Role) String

func (v Role) String() string

type Server

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

Server is a running metrics listener.

func Listen

func Listen(address string, handler http.Handler) (*Server, error)

Listen starts serving metrics at address.

func Serve

func Serve(listener net.Listener, handler http.Handler) *Server

Serve starts serving metrics on a listener reserved during process startup.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr returns the bound listener address.

func (*Server) Done

func (s *Server) Done() <-chan error

Done reports when the listener exits.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully stops the listener.

type ServiceKind

type ServiceKind uint8
const (
	Service ServiceKind = iota + 1
	PublicURL
)

func NormalizeServiceKind

func NormalizeServiceKind(value string) ServiceKind

NormalizeServiceKind translates the service wire value at the boundary.

func (ServiceKind) String

func (v ServiceKind) String() string

type SignalConfig

type SignalConfig struct {
	Endpoint string
	Headers  map[string]string
	Timeout  time.Duration
	TLS      *tls.Config
	Gzip     bool
}

func (SignalConfig) GoString

func (SignalConfig) GoString() string

func (SignalConfig) String

func (SignalConfig) String() string

type TransportValue

type TransportValue uint8
const (
	TransportQUIC TransportValue = iota + 1
	TransportTLSTCP
)

func ParseTransport

func ParseTransport(value string) (TransportValue, bool)

func (TransportValue) String

func (v TransportValue) String() string

type UsageReceiverOutcome

type UsageReceiverOutcome string
const (
	UsageReceiverSuccess         UsageReceiverOutcome = "success"
	UsageReceiverHTTPError       UsageReceiverOutcome = "http_error"
	UsageReceiverTransportError  UsageReceiverOutcome = "transport_error"
	UsageReceiverInvalidResponse UsageReceiverOutcome = "invalid_response"
)

type UsageWorkOutcome

type UsageWorkOutcome string
const (
	UsageWorkSuccess UsageWorkOutcome = "success"
	UsageWorkEmpty   UsageWorkOutcome = "empty"
	UsageWorkError   UsageWorkOutcome = "error"
)

type VisitorOutcome

type VisitorOutcome string

each metric family has its own bounded outcome vocabulary.

const (
	VisitorLookupMissing     VisitorOutcome = "lookup_missing"
	VisitorLookupUnavailable VisitorOutcome = "lookup_unavailable"
	VisitorInvalidProjection VisitorOutcome = "invalid_projection"
	VisitorPolicyDenied      VisitorOutcome = "policy_denied"
	VisitorCapacityDenied    VisitorOutcome = "capacity_denied"
	VisitorOpenFailed        VisitorOutcome = "open_failed"
	VisitorCommittedFailed   VisitorOutcome = "committed_failed"
	VisitorForwarded         VisitorOutcome = "forwarded"
	VisitorDraining          VisitorOutcome = "draining"
	VisitorOther             VisitorOutcome = "other"
)

type Vocabulary

type Vocabulary struct {
	Version          int                    `json:"version"`
	Authority        string                 `json:"authority"`
	CardinalityLimit int                    `json:"cardinality_limit"`
	Attributes       []AttributeDefinition  `json:"attributes"`
	Instruments      []InstrumentDefinition `json:"instruments"`
}

Vocabulary is the deterministic shared contract consumed by tnl.dev.

func SharedVocabulary

func SharedVocabulary() Vocabulary

SharedVocabulary is offline. callbacks expose only local snapshots; no environment, process instance, runtime counts, or I/O is included.

Directories

Path Synopsis
cmd
vocabulary command
Package operatorlog presents typed failures in compact one-line tnld logs.
Package operatorlog presents typed failures in compact one-line tnld logs.
Package publicurlusage defines public URL usage data that can be combined across reports.
Package publicurlusage defines public URL usage data that can be combined across reports.
package serviceaudit defines the allowlisted service audit boundary.
package serviceaudit defines the allowlisted service audit boundary.

Jump to

Keyboard shortcuts

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