Documentation
¶
Overview ¶
Package runtime provides shared process runtime contracts for Eshu services.
The package owns admin HTTP surfaces, metrics endpoints, the opt-in net/http/pprof endpoint, lifecycle wiring, retry policy defaults, API key checks, auto-generated local API key state, and data-store configuration shared by the API, MCP, ingester, reducer, and helper binaries. Recovery routes include work-item replay, refinalize, and collector generation source-level replay requests.
Index ¶
- Constants
- func ApplyNeo4jConfig(target *neo4jconfig.Config, cfg Neo4jConfig)
- func ConfigureMemoryLimit(logger *slog.Logger) int64
- func ConfigurePostgresPool(target PostgresPoolSetter, cfg PostgresConfig)
- func IsTruthy(value string) bool
- func NewAdminMux(cfg AdminMuxConfig) (*http.ServeMux, error)
- func NewCompositeMetricsHandler(statusHandler, prometheusHandler http.Handler) http.Handler
- func NewStatusAdminMux(serviceName string, reader statuspkg.Reader, appHandler http.Handler, ...) (*http.ServeMux, error)
- func NewStatusMetricsHandler(serviceName string, reader statuspkg.Reader) (http.Handler, error)
- func OpenPostgres(ctx context.Context, getenv func(string) string) (*sql.DB, error)
- func ResolveAPIKey(getenv func(string) string) (string, error)
- type AdminCheck
- type AdminMuxConfig
- type Config
- type ContextRunner
- type GraphBackend
- type HTTPServer
- func NewHTTPServer(cfg HTTPServerConfig) (*HTTPServer, error)
- func NewPprofServer(getenv func(string) string) (*HTTPServer, error)
- func NewStatusAdminServer(cfg Config, reader statuspkg.Reader, opts ...StatusAdminOption) (*HTTPServer, error)
- func NewStatusMetricsServer(cfg Config, reader statuspkg.Reader, opts ...StatusAdminOption) (*HTTPServer, error)
- type HTTPServerConfig
- type Lifecycle
- type Neo4jConfig
- type Observability
- type PostgresConfig
- type PostgresPoolSetter
- type ReadinessProbe
- type RecoveryHandler
- type ReindexRequest
- type RequestState
- type RetryPolicyConfig
- type ScanRequest
- type StatusAdminOption
- type StatusRequestHandler
- func (h *StatusRequestHandler) ClaimReindex(ctx context.Context, ingester string) (ReindexRequest, error)
- func (h *StatusRequestHandler) ClaimScan(ctx context.Context, ingester string) (ScanRequest, error)
- func (h *StatusRequestHandler) CompleteReindex(ctx context.Context, ingester string, reindexErr string) error
- func (h *StatusRequestHandler) CompleteScan(ctx context.Context, ingester string, scanErr string) error
- func (h *StatusRequestHandler) RequestReindex(ctx context.Context, ingester string) error
- func (h *StatusRequestHandler) RequestScan(ctx context.Context, ingester string) error
- type StatusRequestStore
Constants ¶
const ( // DefaultMemLimitRatio is the fraction of container memory to use as // GOMEMLIMIT. 70% leaves headroom for non-heap allocations (goroutine // stacks, mmap'd files, cgo, kernel page cache). DefaultMemLimitRatio = 0.70 // MinMemLimit is the floor — never set GOMEMLIMIT below this. MinMemLimit = 512 << 20 // 512 MiB )
const PprofAddrEnvVar = "ESHU_PPROF_ADDR"
PprofAddrEnvVar is the env var that controls the opt-in pprof endpoint. Operators set it to bind the runtime profiler; leaving it unset disables the endpoint entirely.
Variables ¶
This section is empty.
Functions ¶
func ApplyNeo4jConfig ¶
func ApplyNeo4jConfig(target *neo4jconfig.Config, cfg Neo4jConfig)
ApplyNeo4jConfig applies the shared Neo4j tuning policy to a driver config.
func ConfigureMemoryLimit ¶
ConfigureMemoryLimit sets GOMEMLIMIT based on:
- GOMEMLIMIT env var (explicit override via Go runtime, highest priority)
- Container cgroup memory limit × DefaultMemLimitRatio
- No-op if neither is available (let Go defaults apply)
It also unconditionally sets GODEBUG=madvdontneed=1 which forces the Go runtime to release RSS pages to the OS immediately on GC. This prevents the kernel OOM killer from targeting the container based on inflated RSS.
Returns the applied limit in bytes, or 0 if no limit was set.
func ConfigurePostgresPool ¶
func ConfigurePostgresPool(target PostgresPoolSetter, cfg PostgresConfig)
ConfigurePostgresPool applies the shared Postgres pool policy to a target.
func IsTruthy ¶
IsTruthy reports whether value is one of the accepted truthy spellings for an Eshu boolean environment-variable flag (case-insensitive, surrounding whitespace trimmed). It is the single source of truth for the "is this escape-hatch/opt-in flag on" question across runtime env-var flags such as ESHU_AUTO_GENERATE_API_KEY and ESHU_MCP_ALLOW_UNAUTHENTICATED.
func NewAdminMux ¶
func NewAdminMux(cfg AdminMuxConfig) (*http.ServeMux, error)
NewAdminMux builds the shared probe and admin route contract for a runtime.
func NewCompositeMetricsHandler ¶
NewCompositeMetricsHandler serves OTEL Prometheus output and the hand-rolled runtime gauges from the same /metrics endpoint.
func NewStatusAdminMux ¶
func NewStatusAdminMux( serviceName string, reader statuspkg.Reader, appHandler http.Handler, opts ...StatusAdminOption, ) (*http.ServeMux, error)
NewStatusAdminMux builds the shared status, metrics, recovery, and optional application routes for a long-running Go runtime.
func NewStatusMetricsHandler ¶
NewStatusMetricsHandler builds a shared Prometheus-style metrics surface from the same status reader used by the runtime admin report.
func OpenPostgres ¶
OpenPostgres opens, tunes, and verifies a Postgres connection for a Go service runtime.
func ResolveAPIKey ¶
ResolveAPIKey returns the runtime API token contract for local compose and operator deployments.
Resolution order:
- explicit ESHU_API_KEY environment variable
- persisted ESHU_HOME/.env entry
- auto-generated token when ESHU_AUTO_GENERATE_API_KEY is truthy
When a token is persisted or generated, it is written back to the .env file so the CLI and follow-on runtimes can reuse the same contract.
Types ¶
type AdminCheck ¶
type AdminCheck func() error
AdminCheck reports whether a runtime probe is healthy.
type AdminMuxConfig ¶
type AdminMuxConfig struct {
ServiceName string
Health AdminCheck
Ready AdminCheck
StatusHandler http.Handler
MetricsHandler http.Handler
RecoveryHandler *RecoveryHandler
}
AdminMuxConfig defines the shared admin and probe routes for a long-running Go runtime.
type Config ¶
Config captures the minimal shared process settings for the Go data-plane bootstrap lane.
func LoadConfig ¶
LoadConfig builds a validated runtime config for the named service.
type ContextRunner ¶
type ContextRunner struct{}
ContextRunner blocks until the parent process context is canceled.
type GraphBackend ¶
type GraphBackend string
GraphBackend names the graph database adapter selected for a Eshu runtime.
const ( // GraphBackendNeo4j selects the official Neo4j graph adapter. GraphBackendNeo4j GraphBackend = "neo4j" // GraphBackendNornicDB selects the official NornicDB graph adapter. GraphBackendNornicDB GraphBackend = "nornicdb" )
func LoadGraphBackend ¶
func LoadGraphBackend(getenv func(string) string) (GraphBackend, error)
LoadGraphBackend validates the selected graph backend for the current process. Empty uses the NornicDB default.
type HTTPServer ¶
type HTTPServer struct {
// contains filtered or unexported fields
}
HTTPServer owns one runtime-mounted HTTP server and graceful shutdown path.
func NewHTTPServer ¶
func NewHTTPServer(cfg HTTPServerConfig) (*HTTPServer, error)
NewHTTPServer validates and freezes the shared HTTP server lifecycle config.
func NewPprofServer ¶
func NewPprofServer(getenv func(string) string) (*HTTPServer, error)
NewPprofServer builds the opt-in pprof HTTP server for a runtime binary.
When ESHU_PPROF_ADDR is unset or whitespace-only, the function returns (nil, nil); every caller must check for a nil *HTTPServer before calling Start, matching the precedent set by NewStatusMetricsServer.
When the env value supplies only a port (":6060"), the bind host is forced to 127.0.0.1 so a typo or a habit picked up from public listeners does not silently expose profiling endpoints on a routable interface. Explicit hosts — including 0.0.0.0 — are preserved.
func NewStatusAdminServer ¶
func NewStatusAdminServer(cfg Config, reader statuspkg.Reader, opts ...StatusAdminOption) (*HTTPServer, error)
NewStatusAdminServer builds the shared admin HTTP server for a long-running runtime using the storage-backed status reader seam.
func NewStatusMetricsServer ¶
func NewStatusMetricsServer(cfg Config, reader statuspkg.Reader, opts ...StatusAdminOption) (*HTTPServer, error)
NewStatusMetricsServer builds the shared dedicated metrics HTTP server for a long-running runtime when a separate metrics address is configured.
func (*HTTPServer) Addr ¶
func (s *HTTPServer) Addr() string
Addr returns the bound address after Start.
type HTTPServerConfig ¶
HTTPServerConfig configures a shared runtime-owned HTTP server lifecycle.
type Lifecycle ¶
Lifecycle is the minimal start-run-stop surface shared by the bootstrap lane.
func NewLifecycle ¶
NewLifecycle builds a lifecycle wrapper for the supplied config.
type Neo4jConfig ¶
type Neo4jConfig struct {
URI string
Username string
Password string
DatabaseName string
MaxConnectionPoolSize int
MaxConnectionLifetime time.Duration
ConnectionAcquisitionTimeout time.Duration
SocketConnectTimeout time.Duration
VerifyTimeout time.Duration
}
Neo4jConfig captures shared driver and pool tuning for Go services that talk to Neo4j.
func LoadNeo4jConfig ¶
func LoadNeo4jConfig(getenv func(string) string) (Neo4jConfig, error)
LoadNeo4jConfig reads the shared Neo4j config from env.
func OpenNeo4jDriver ¶
func OpenNeo4jDriver( ctx context.Context, getenv func(string) string, ) (neo4jdriver.DriverWithContext, Neo4jConfig, error)
OpenNeo4jDriver opens and verifies a Neo4j driver with shared pool tuning.
type Observability ¶
Observability carries the frozen OTEL contract through bootstrap wiring.
func NewObservability ¶
func NewObservability() Observability
NewObservability snapshots the shared telemetry contract for a service.
type PostgresConfig ¶
type PostgresConfig struct {
DSN string
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime time.Duration
ConnMaxIdleTime time.Duration
PingTimeout time.Duration
}
PostgresConfig captures the shared database and pool tuning used by Go services that talk to Postgres.
func LoadPostgresConfig ¶
func LoadPostgresConfig(getenv func(string) string) (PostgresConfig, error)
LoadPostgresConfig reads the shared Postgres config from env.
type PostgresPoolSetter ¶
type PostgresPoolSetter interface {
SetMaxOpenConns(int)
SetMaxIdleConns(int)
SetConnMaxLifetime(time.Duration)
SetConnMaxIdleTime(time.Duration)
}
PostgresPoolSetter is the minimal tuning surface required from sql.DB.
type ReadinessProbe ¶
type ReadinessProbe struct {
// Name labels the dependency in the /readyz cause body (e.g. "postgres").
Name string
// Timeout bounds this probe; non-positive values fall back to
// defaultDependencyReadinessTimeout.
Timeout time.Duration
// Check reports the dependency error, or nil when the dependency is ready.
Check func(ctx context.Context) error
}
ReadinessProbe is a single named dependency check evaluated by /readyz. Each probe is run with a bounded timeout and contributes its cause to the aggregated readiness failure body when it fails.
func GraphReadinessProbe ¶
func GraphReadinessProbe(driver neo4jdriver.DriverWithContext, timeout time.Duration) ReadinessProbe
GraphReadinessProbe verifies graph backend (Bolt) connectivity for /readyz. The same Bolt driver fronts both Neo4j and NornicDB, so one probe covers both backends. A nil driver (for example the local lightweight profile that disables the graph) reports ready so readiness is not gated on a dependency the service does not use.
func PostgresReadinessProbe ¶
func PostgresReadinessProbe(db *sql.DB, timeout time.Duration) ReadinessProbe
PostgresReadinessProbe verifies Postgres connectivity for /readyz using a bounded Ping. A blocked Ping surfaces as a deadline-exceeded cause, which distinguishes pool exhaustion or an unreachable database from a schema fault reported by the status snapshot probe.
func ReadinessProbesForDependencies ¶
func ReadinessProbesForDependencies(db *sql.DB, driver neo4jdriver.DriverWithContext) []ReadinessProbe
ReadinessProbesForDependencies builds the standard dependency readiness probes for a long-running service, omitting dependencies that are not wired. A nil db yields no Postgres probe; a nil graph driver yields no graph probe, so the local lightweight profile that disables the graph stays ready. In production wiring both handles are non-nil, so both dependencies are probed.
type RecoveryHandler ¶
type RecoveryHandler struct {
// contains filtered or unexported fields
}
RecoveryHandler provides HTTP endpoints for write-plane recovery operations. It replaces the Python admin refinalize and replay surfaces with Go-owned queue replay rather than direct graph mutation.
func NewRecoveryHandler ¶
func NewRecoveryHandler(handler *recovery.Handler) (*RecoveryHandler, error)
NewRecoveryHandler constructs the HTTP recovery handler.
func (*RecoveryHandler) Mount ¶
func (h *RecoveryHandler) Mount(mux *http.ServeMux)
Mount registers recovery routes on the given mux.
type ReindexRequest ¶
type ReindexRequest struct {
Ingester string
State RequestState
RequestedAt time.Time
ClaimedAt time.Time
CompletedAt time.Time
Error string
}
ReindexRequest captures the current state of a reindex lifecycle for one ingester.
type RequestState ¶
type RequestState string
RequestState represents the lifecycle state of a scan or reindex request.
const ( // RequestStateIdle means no scan or reindex request is currently active. RequestStateIdle RequestState = "idle" // RequestStatePending means the request has been stored but not claimed. RequestStatePending RequestState = "pending" // RequestStateRunning means a runtime has claimed and started the request. RequestStateRunning RequestState = "running" // RequestStateCompleted means the claimed request finished successfully. RequestStateCompleted RequestState = "completed" // RequestStateFailed means the claimed request ended with an error. RequestStateFailed RequestState = "failed" )
func (RequestState) Validate ¶
func (s RequestState) Validate() error
Validate returns an error if the state is not a known value.
type RetryPolicyConfig ¶
type RetryPolicyConfig struct {
MaxAttempts int
RetryDelay time.Duration
// MaxRetryDelay caps the exponential backoff term so a high attempt
// count cannot grow the delay unboundedly. Zero/unset falls back to
// defaultRetryMaxDelay (1 hour).
MaxRetryDelay time.Duration
// JitterFraction scales the random component added on top of the
// exponential term, relative to RetryDelay. A value of 0 disables
// jitter entirely (deterministic legacy behavior); the default 0.1
// matches the formula in issue #4450: rand(0, baseDelay*0.1).
JitterFraction float64
}
RetryPolicyConfig captures bounded retry settings for one runtime stage.
RetryDelay is the base delay; the actual per-attempt delay grows exponentially with the durable attempt count (baseDelay*(1<<attempt)), capped at MaxRetryDelay, plus a uniform random jitter term drawn from [0, RetryDelay*JitterFraction). Fixed, jitter-free delays let many work items that fail at the same instant reconverge on the identical visible_at and self-reinforce into a retry storm that starves new work (#4450); the exponential term and jitter both exist to break that synchronization.
func LoadRetryPolicyConfig ¶
func LoadRetryPolicyConfig(getenv func(string) string, stagePrefix string) (RetryPolicyConfig, error)
LoadRetryPolicyConfig reads a bounded retry policy using the supplied stage prefix, for example PROJECTOR or REDUCER.
type ScanRequest ¶
type ScanRequest struct {
Ingester string
State RequestState
RequestedAt time.Time
ClaimedAt time.Time
CompletedAt time.Time
Error string
}
ScanRequest captures the current state of a scan lifecycle for one ingester.
type StatusAdminOption ¶
type StatusAdminOption func(*statusAdminOptions)
StatusAdminOption configures optional behavior on the status admin server.
func WithPrometheusHandler ¶
func WithPrometheusHandler(h http.Handler) StatusAdminOption
WithPrometheusHandler attaches an OTEL Prometheus exporter handler that is served alongside the existing status-based metrics on /metrics.
func WithReadinessProbes ¶
func WithReadinessProbes(probes ...ReadinessProbe) StatusAdminOption
WithReadinessProbes registers additional dependency checks that /readyz must pass before reporting ready. The status-snapshot probe (Postgres + schema) always runs as the baseline; these probes extend it, for example to verify graph backend connectivity. Each probe runs under its own bounded timeout and contributes its cause to the readiness failure body.
func WithRecoveryHandler ¶
func WithRecoveryHandler(rh *RecoveryHandler) StatusAdminOption
WithRecoveryHandler attaches a recovery handler to the admin mux, mounting /admin/replay and /admin/refinalize routes alongside the standard probes.
type StatusRequestHandler ¶
type StatusRequestHandler struct {
// contains filtered or unexported fields
}
StatusRequestHandler manages scan/reindex lifecycle transitions.
func NewStatusRequestHandler ¶
func NewStatusRequestHandler(store StatusRequestStore) (*StatusRequestHandler, error)
NewStatusRequestHandler constructs a handler with the given store.
func (*StatusRequestHandler) ClaimReindex ¶
func (h *StatusRequestHandler) ClaimReindex(ctx context.Context, ingester string) (ReindexRequest, error)
ClaimReindex claims a pending reindex request for the given ingester.
func (*StatusRequestHandler) ClaimScan ¶
func (h *StatusRequestHandler) ClaimScan(ctx context.Context, ingester string) (ScanRequest, error)
ClaimScan claims a pending scan request for the given ingester.
func (*StatusRequestHandler) CompleteReindex ¶
func (h *StatusRequestHandler) CompleteReindex(ctx context.Context, ingester string, reindexErr string) error
CompleteReindex marks a running reindex as completed or failed.
func (*StatusRequestHandler) CompleteScan ¶
func (h *StatusRequestHandler) CompleteScan(ctx context.Context, ingester string, scanErr string) error
CompleteScan marks a running scan as completed or failed.
func (*StatusRequestHandler) RequestReindex ¶
func (h *StatusRequestHandler) RequestReindex(ctx context.Context, ingester string) error
RequestReindex initiates a reindex request for the given ingester.
func (*StatusRequestHandler) RequestScan ¶
func (h *StatusRequestHandler) RequestScan(ctx context.Context, ingester string) error
RequestScan initiates a scan request for the given ingester.
type StatusRequestStore ¶
type StatusRequestStore interface {
// RequestScan transitions a scan request from idle to pending.
RequestScan(ctx context.Context, ingester string, now time.Time) error
// ClaimScanRequest transitions a pending scan to running.
ClaimScanRequest(ctx context.Context, ingester string, now time.Time) (ScanRequest, error)
// CompleteScanRequest transitions a running scan to completed or failed.
CompleteScanRequest(ctx context.Context, ingester string, now time.Time, scanErr string) error
// RequestReindex transitions a reindex request from idle to pending.
RequestReindex(ctx context.Context, ingester string, now time.Time) error
// ClaimReindexRequest transitions a pending reindex to running.
ClaimReindexRequest(ctx context.Context, ingester string, now time.Time) (ReindexRequest, error)
// CompleteReindexRequest transitions a running reindex to completed or failed.
CompleteReindexRequest(ctx context.Context, ingester string, now time.Time, reindexErr string) error
// GetScanState returns the current scan request state for one ingester.
GetScanState(ctx context.Context, ingester string) (ScanRequest, error)
// GetReindexState returns the current reindex request state for one ingester.
GetReindexState(ctx context.Context, ingester string) (ReindexRequest, error)
}
StatusRequestStore provides the durable scan/reindex request lifecycle operations ported from the Python status_store_db.