observability

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package observability provides metrics, access logging, and audit logging for the gateway.

Index

Constants

View Source
const (
	MetricUpstreamRequestDuration = "bastion_upstream_request_duration_seconds"
	MetricRequestsRejected        = "bastion_requests_rejected_total"
	MetricRetriesAttempted        = "bastion_retries_attempted_total"
	MetricCircuitTransitions      = "bastion_circuit_breakers_transitioned_total"
	MetricUpstreamTargets         = "bastion_upstream_targets"
	MetricActiveStreams           = "bastion_active_streams"
	MetricBackgroundJobDuration   = "bastion_background_job_duration_seconds"
)

Metric names. Forge exports them with its namespace in front, so bastion_upstream_request_duration_seconds scrapes as forge_bastion_upstream_request_duration_seconds.

View Source
const (
	// StatusClassError is an attempt that got no response: the dial, the
	// TLS handshake or the round trip failed, or it timed out.
	StatusClassError = "error"

	// StatusClassCanceled is an attempt abandoned because the client went
	// away first.
	StatusClassCanceled = "canceled"
)

Status classes reported on bastion_upstream_request_duration_seconds besides 1xx to 5xx.

Variables

This section is empty.

Functions

func StatusClass

func StatusClass(status int, err error) string

StatusClass turns the outcome of an upstream attempt into the status_class label: 1xx to 5xx for a response, StatusClassCanceled when the client went away, StatusClassError for any other failure.

Types

type AccessLogConfig

type AccessLogConfig struct {
	Enabled        bool     `json:"enabled" yaml:"enabled"`
	RedactHeaders  []string `json:"redactHeaders,omitempty" yaml:"redact_headers"`
	IncludeBody    bool     `json:"includeBody" yaml:"include_body"`
	MaxBodyLogSize int      `json:"maxBodyLogSize" yaml:"max_body_log_size"`
}

AccessLogConfig holds access logging settings.

type AccessLogger

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

AccessLogger provides structured access logging for gateway requests.

func NewAccessLogger

func NewAccessLogger(config AccessLogConfig, logger forge.Logger) *AccessLogger

NewAccessLogger creates a new access logger.

func (*AccessLogger) Log

func (al *AccessLogger) Log(r *http.Request, statusCode int, latency time.Duration, route *RouteInfo, target *TargetInfo)

Log logs a gateway request.

func (*AccessLogger) LogAdminAction

func (al *AccessLogger) LogAdminAction(action, resource, result string, r *http.Request)

LogAdminAction logs an admin API action.

type AuditAction

type AuditAction string

AuditAction represents the type of admin action taken.

const (
	AuditRouteCreated    AuditAction = "route.created"
	AuditRouteUpdated    AuditAction = "route.updated"
	AuditRouteDeleted    AuditAction = "route.deleted"
	AuditRouteToggled    AuditAction = "route.toggled"
	AuditConfigChanged   AuditAction = "config.changed"
	AuditDiscoveryForced AuditAction = "discovery.forced"
	AuditCircuitReset    AuditAction = "circuit.reset"
	AuditCacheCleared    AuditAction = "cache.cleared"
)

type AuditConfig

type AuditConfig struct {
	// Enabled enables audit logging.
	Enabled bool `json:"enabled" yaml:"enabled"`

	// BufferSize is the channel buffer for async audit events.
	BufferSize int `json:"bufferSize" yaml:"buffer_size"`
}

AuditConfig configures audit logging.

type AuditEvent

type AuditEvent struct {
	Timestamp time.Time      `json:"timestamp"`
	Action    AuditAction    `json:"action"`
	Actor     string         `json:"actor"`
	Resource  string         `json:"resource"`
	Detail    map[string]any `json:"detail,omitempty"`
	Result    string         `json:"result"` // "success" or "failure"
	Error     string         `json:"error,omitempty"`
}

AuditEvent represents an auditable action in the gateway.

type AuditLogger

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

AuditLogger captures and dispatches administrative audit events.

func NewAuditLogger

func NewAuditLogger(config AuditConfig, logger forge.Logger) *AuditLogger

NewAuditLogger creates a new audit logger.

func (*AuditLogger) AddSink

func (al *AuditLogger) AddSink(sink AuditSink)

AddSink adds an audit sink for consuming events.

func (*AuditLogger) Record

func (al *AuditLogger) Record(action AuditAction, actor, resource string, detail map[string]any, err error)

Record emits an audit event. Non-blocking; drops events if buffer is full.

func (*AuditLogger) Start

func (al *AuditLogger) Start()

Start begins processing audit events asynchronously.

func (*AuditLogger) Stop

func (al *AuditLogger) Stop()

Stop flushes remaining events and stops the audit logger.

type AuditSink

type AuditSink interface {
	// Write persists an audit event.
	Write(ctx context.Context, event *AuditEvent) error
}

AuditSink is the interface for consuming audit events.

type CircuitState

type CircuitState string

CircuitState represents the state of a circuit breaker.

const (
	// CircuitClosed allows requests through (normal operation).
	CircuitClosed CircuitState = "closed"

	// CircuitOpen rejects requests (fail-fast).
	CircuitOpen CircuitState = "open"

	// CircuitHalfOpen allows limited probe requests.
	CircuitHalfOpen CircuitState = "half_open"
)

type Job

type Job string

Job is the job label of bastion_background_job_duration_seconds.

const (
	JobDiscovery   Job = "discovery"
	JobOpenAPI     Job = "openapi"
	JobAsyncAPI    Job = "asyncapi"
	JobHealthCheck Job = "health_check"
)

The job label's values.

type LogAuditSink

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

LogAuditSink writes audit events as structured log entries.

func NewLogAuditSink

func NewLogAuditSink(logger forge.Logger) *LogAuditSink

NewLogAuditSink creates a sink that writes to a forge.Logger.

func (*LogAuditSink) Write

func (s *LogAuditSink) Write(_ context.Context, event *AuditEvent) error

Write logs the audit event.

type Metrics

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

Metrics records the gateway's metrics through Forge's metrics. Every label is a small fixed enum: route IDs, target IDs, URLs, hosts and service names never become labels.

A nil *Metrics records nothing, so callers don't have to check.

func NewMetrics

func NewMetrics(m forge.Metrics, config MetricsConfig) *Metrics

NewMetrics declares the gateway's metrics on m. It returns nil, which records nothing, when config.Enabled is false or m is nil.

func (*Metrics) CircuitTransitioned

func (gm *Metrics) CircuitTransitioned(state CircuitState)

CircuitTransitioned counts a circuit breaker moving into state.

func (*Metrics) ObserveJob

func (gm *Metrics) ObserveJob(job Job, failed bool, d time.Duration)

ObserveJob records one run of a background job. failed is true when the run, or at least one unit of work inside it, failed.

func (*Metrics) ObserveUpstream

func (gm *Metrics) ObserveUpstream(protocol Protocol, statusClass string, d time.Duration)

ObserveUpstream records one attempt to reach an upstream. statusClass comes from StatusClass.

func (*Metrics) RequestRejected

func (gm *Metrics) RequestRejected(reason RejectReason)

RequestRejected counts a request the gateway answered itself.

func (*Metrics) RetryBudgetExhausted

func (gm *Metrics) RetryBudgetExhausted()

RetryBudgetExhausted counts a retry the policy asked for and the target's retry budget refused.

func (*Metrics) RetrySent

func (gm *Metrics) RetrySent()

RetrySent counts a retry that went out.

func (*Metrics) SetUpstreamTargets

func (gm *Metrics) SetUpstreamTargets(healthy, unhealthy int)

SetUpstreamTargets sets how many monitored upstream targets are healthy and unhealthy right now.

func (*Metrics) StreamStarted

func (gm *Metrics) StreamStarted(protocol Protocol) (done func())

StreamStarted counts a WebSocket, SSE or gRPC stream as open until the returned func is called. Calling it more than once is harmless.

type MetricsConfig

type MetricsConfig struct {
	// Enabled turns the gateway's metrics on. They are recorded through the
	// Forge app's metrics, so the app's own metrics have to be on as well.
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Prefix is ignored. The metric names are fixed (see the Metric*
	// constants) and Forge adds its namespace in front of them. The field
	// is kept so existing configuration still parses.
	Prefix string `json:"prefix,omitempty" yaml:"prefix"`
}

MetricsConfig holds metrics settings used by the Metrics collector.

type Protocol

type Protocol string

Protocol is the protocol label: how the gateway talks to the upstream.

const (
	ProtocolHTTP      Protocol = "http"
	ProtocolWebSocket Protocol = "websocket"
	ProtocolSSE       Protocol = "sse"
	ProtocolGRPC      Protocol = "grpc"
)

The protocol label's values.

type RejectReason

type RejectReason string

RejectReason is the reason label of bastion_requests_rejected_total: why the gateway answered a request itself instead of sending it upstream.

const (
	RejectDraining          RejectReason = "draining"
	RejectIPFiltered        RejectReason = "ip_filtered"
	RejectGlobalRateLimit   RejectReason = "global_rate_limit"
	RejectRouteRateLimit    RejectReason = "route_rate_limit"
	RejectNoRoute           RejectReason = "no_route"
	RejectPathBlocked       RejectReason = "path_blocked"
	RejectUnauthenticated   RejectReason = "unauthenticated"
	RejectForbidden         RejectReason = "forbidden"
	RejectAuthUnavailable   RejectReason = "auth_unavailable"
	RejectHook              RejectReason = "hook"
	RejectCircuitOpen       RejectReason = "circuit_open"
	RejectNoHealthyUpstream RejectReason = "no_healthy_upstream"
)

The reason label's values.

type RouteInfo

type RouteInfo struct {
	ID       string
	Path     string
	Protocol string
	Source   string
}

RouteInfo holds the route metadata needed for access logging.

type TargetInfo

type TargetInfo struct {
	ID  string
	URL string
}

TargetInfo holds the target metadata needed for access logging.

Jump to

Keyboard shortcuts

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