From 51d780ee7f94cdaaf3f627fe1713a7c393f579ab Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:16:20 -0600 Subject: [PATCH 01/15] fix(errors): expose internal error text only in an explicit development environment 5xx bodies carried the raw error text in every environment except exactly "production". An app deployed with the environment unset, or set to "prod" or "staging", sent driver errors to any client that could trigger one, and a pq error names the host, the database and the user. Error text is now exposed only when Environment is explicitly development, dev, local or test (case-insensitive). Anything else redacts, including an unset environment. Environment still defaults to "development" for everything else it drives (log format, sampling ratio, the banner), but that default is now recorded as a placeholder: an app built from New() or DefaultAppConfig() without choosing an environment counts as unset and redacts. WithAppEnvironment("development") or a literal AppConfig with Environment "development" still exposes. AppConfig.ExposeInternalErrors and WithExposeInternalErrors override the environment either way. Logs keep the full error in every case. --- app.go | 55 +++++++++++++++++++++++++++++ app_error_exposure_test.go | 71 ++++++++++++++++++++++++++++++++++++++ app_impl.go | 20 ++++++++--- 3 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 app_error_exposure_test.go diff --git a/app.go b/app.go index 1119b51d..db9f6865 100644 --- a/app.go +++ b/app.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "os" + "strings" "time" ) @@ -125,6 +126,12 @@ type AppConfig struct { ShutdownTimeout time.Duration // Default: 30s ShutdownSignals []os.Signal // Default: SIGINT, SIGTERM + // ExposeInternalErrors decides whether 5xx responses carry the internal + // error text. Nil means it follows Environment: only an explicitly set + // development, dev, local or test environment exposes it. An unset or + // unrecognised environment, including staging and prod, redacts. + ExposeInternalErrors *bool + // Health HealthGracePeriod time.Duration // Grace period after startup during which health endpoints always return 200. Default: 60s @@ -171,6 +178,11 @@ type AppConfig struct { // metricsConfigSet records a WithAppMetricsConfig call, so a config equal // to the defaults still counts as set in code. metricsConfigSet bool + + // environmentDefaulted marks the "development" that DefaultAppConfig puts + // in Environment as a placeholder rather than a choice. Security defaults + // treat it as unset; see environmentIsDevelopment. + environmentDefaulted bool } // DefaultAppConfig returns a default application configuration. @@ -206,6 +218,8 @@ func DefaultAppConfig() AppConfig { EnableEnvConfig: true, // Enabled by default EnvSeparator: "_", // Standard separator EnvOverridesFile: true, // Env takes precedence over files by default + + environmentDefaulted: true, } } @@ -244,6 +258,7 @@ func WithAppDescription(description string) AppOption { func WithAppEnvironment(environment string) AppOption { return func(c *AppConfig) { c.Environment = environment + c.environmentDefaulted = false } } @@ -485,6 +500,46 @@ func WithWebSocketOrigins(origins ...string) AppOption { } } +// WithExposeInternalErrors overrides whether 5xx responses carry the internal +// error text, whatever the environment. See AppConfig.ExposeInternalErrors. +func WithExposeInternalErrors(expose bool) AppOption { + return func(c *AppConfig) { c.ExposeInternalErrors = &expose } +} + +// developmentEnvironments are the Environment values that turn on the +// debugging defaults. Compared case-insensitively. +var developmentEnvironments = map[string]bool{ + "development": true, + "dev": true, + "local": true, + "test": true, +} + +// environmentIsDevelopment reports whether config names a development +// environment on purpose. An empty Environment is unset, and so is the +// "development" placeholder DefaultAppConfig fills in when nothing replaced +// it: an app deployed without setting its environment must get the +// production-safe behaviour, not the debugging one. +func environmentIsDevelopment(config AppConfig) bool { + env := strings.ToLower(strings.TrimSpace(config.Environment)) + if env == "" || (config.environmentDefaulted && env == "development") { + return false + } + + return developmentEnvironments[env] +} + +// resolveExposeInternalErrors applies an explicit ExposeInternalErrors first +// and otherwise exposes error text only in an explicit development +// environment. +func resolveExposeInternalErrors(config AppConfig, devEnvironment bool) bool { + if config.ExposeInternalErrors != nil { + return *config.ExposeInternalErrors + } + + return devEnvironment +} + // NewApp creates a new Forge application. func NewApp(config AppConfig) App { return newApp(config) diff --git a/app_error_exposure_test.go b/app_error_exposure_test.go new file mode 100644 index 00000000..1074f736 --- /dev/null +++ b/app_error_exposure_test.go @@ -0,0 +1,71 @@ +package forge + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/xraph/forge/internal/shared" +) + +// 5xx bodies used to carry the internal error text in every environment +// except exactly "production", so an unset environment, "prod" or "staging" +// sent driver errors with hosts, users and databases to any client. +func TestExposeInternalErrors_OnlyExplicitDevelopment(t *testing.T) { + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + t.Cleanup(func() { shared.SetExposeInternalErrors(false) }) + + tru, fals := true, false + + cases := []struct { + name string + build func() App + expose bool + }{ + {"New with no environment", func() App { return New() }, false}, + {"DefaultAppConfig untouched", func() App { return NewApp(DefaultAppConfig()) }, false}, + {"empty literal", func() App { return NewApp(AppConfig{}) }, false}, + {"prod", func() App { return New(WithAppEnvironment("prod")) }, false}, + {"staging", func() App { return New(WithAppEnvironment("staging")) }, false}, + {"production", func() App { return New(WithAppEnvironment("production")) }, false}, + {"typo", func() App { return New(WithAppEnvironment("developmnet")) }, false}, + {"development option", func() App { return New(WithAppEnvironment("development")) }, true}, + {"Development literal", func() App { return NewApp(AppConfig{Environment: "Development"}) }, true}, + {"dev", func() App { return New(WithAppEnvironment("dev")) }, true}, + {"local", func() App { return New(WithAppEnvironment("local")) }, true}, + {"test", func() App { return New(WithAppEnvironment("test")) }, true}, + {"override on in production", func() App { + return NewApp(AppConfig{Environment: "production", ExposeInternalErrors: &tru}) + }, true}, + {"override off in development", func() App { + return New(WithAppEnvironment("development"), WithExposeInternalErrors(false)) + }, false}, + {"override off literal", func() App { + return NewApp(AppConfig{Environment: "test", ExposeInternalErrors: &fals}) + }, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + a := tc.build() + + _ = a.Router().GET("/boom", func(Context) error { + return InternalError(errors.New(`pq: password authentication failed for user "app_rw" host=10.0.3.17 database=prod`)) + }) + + w := httptest.NewRecorder() + a.Router().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/boom", nil)) + + if w.Code != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500", w.Code) + } + + leaked := strings.Contains(w.Body.String(), "10.0.3.17") + if leaked != tc.expose { + t.Errorf("error text in body = %v, want %v; body %s", leaked, tc.expose, w.Body.String()) + } + }) + } +} diff --git a/app_impl.go b/app_impl.go index e869eb1d..671af2c7 100644 --- a/app_impl.go +++ b/app_impl.go @@ -68,6 +68,11 @@ type app struct { mu sync.RWMutex started bool starting bool + + // devEnvironment reports whether Environment was explicitly set to a + // development one. It gates the defaults that trade safety for debugging + // convenience: internal error text in 5xx bodies and health check detail. + devEnvironment bool } // newApp creates a new app instance. @@ -81,6 +86,10 @@ func newApp(config AppConfig) *app { config.Version = "1.0.0" } + // Decide before the default below fills the field in: an unset + // environment must not count as a development one. + devEnvironment := environmentIsDevelopment(config) + if config.Environment == "" { config.Environment = "development" } @@ -307,10 +316,12 @@ func newApp(config AppConfig) *app { routerOpts = append(routerOpts, internalrouter.WithHTTPAddress(config.HTTPAddress)) } - // Internal error text is echoed to clients only outside production, where - // it aids debugging; in production a 500 carries no detail. Logs always have - // the full error either way. - shared.SetExposeInternalErrors(config.Environment != "production") + // Internal error text is echoed to clients only in an environment that + // was explicitly named as a development one, where it aids debugging. + // Anything else (unset, staging, prod, a typo) gets a 500 with no detail, + // because a driver error routinely carries hostnames, users and DSNs. + // Logs always have the full error either way. + shared.SetExposeInternalErrors(resolveExposeInternalErrors(config, devEnvironment)) // Cap request bodies. Zero leaves the router's own default in place. if config.MaxRequestBodySize != 0 { @@ -418,6 +429,7 @@ func newApp(config AppConfig) *app { codeMetrics: codeMetrics, extensions: []Extension{}, // Initialize empty, will populate below startTime: time.Now(), + devEnvironment: devEnvironment, } // Register extensions from config From 9b5ab104f5227057d2868eb45bd65f1847cecbe3 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:17:51 -0600 Subject: [PATCH 02/15] fix(health): keep raw check errors out of public health responses /_/health, /_/info and /_/metrics are served on the main listener with no way to restrict them. The extension health check put err.Error() into the result's details, so /_/health returned whatever the extension's error said: in practice a driver error with the DSN, user and password. /_/info listed every service, extension and version to anyone, and an unhealthy app logged a warning on every probe, since every probe reads the same cached report. - The extension check no longer puts the error in its result. The error is logged instead, once per distinct error rather than every check round, with a line when the extension recovers. - AppConfig.ObservabilityGuard (WithObservabilityGuard) authorizes the detailed endpoints. A denied caller gets only the overall status and each check's status from /_/health, and a 404 from /_/info and /_/metrics. Without a guard, /_/health shows details only in an explicit development environment, since check messages are free text. - /_/info is opt-in (EnableInfoEndpoint, WithInfoEndpoint), and warns when enabled outside development without a guard. - The unhealthy warning is logged once per report instead of per request, and names the failing checks. /_/health/live and /_/health/ready never consult the guard, so orchestrator probes need no credentials. --- app.go | 35 +++++ app_impl.go | 141 +++++++++++++++++++- app_observability_guard_test.go | 228 ++++++++++++++++++++++++++++++++ app_test.go | 13 +- 4 files changed, 404 insertions(+), 13 deletions(-) create mode 100644 app_observability_guard_test.go diff --git a/app.go b/app.go index db9f6865..5072a835 100644 --- a/app.go +++ b/app.go @@ -126,6 +126,22 @@ type AppConfig struct { ShutdownTimeout time.Duration // Default: 30s ShutdownSignals []os.Signal // Default: SIGINT, SIGTERM + // ObservabilityGuard authorizes access to the detailed observability + // endpoints: the per-check detail of /_/health, /_/info and /_/metrics. + // Return false to deny. A denied /_/health caller still gets the overall + // status and the status of each check, without messages or details, and a + // denied /_/info or /_/metrics caller gets a 404. /_/health/live and + // /_/health/ready never consult the guard, so orchestrator probes keep + // working without credentials. + // + // Nil means /_/metrics and an enabled /_/info are open, and /_/health + // shows details only when Environment is explicitly a development one + // (development, dev, local or test). + ObservabilityGuard func(*http.Request) bool + + // EnableInfoEndpoint registers /_/info, which lists the services, + // extensions, versions and Go version the app runs. Default: false. + EnableInfoEndpoint bool // ExposeInternalErrors decides whether 5xx responses carry the internal // error text. Nil means it follows Environment: only an explicitly set // development, dev, local or test environment exposes it. An unset or @@ -500,6 +516,25 @@ func WithWebSocketOrigins(origins ...string) AppOption { } } +// WithObservabilityGuard restricts the detailed observability endpoints. The +// guard runs on every request to /_/health, /_/info and /_/metrics; see +// AppConfig.ObservabilityGuard for what a denied caller sees. +// +// forge.WithObservabilityGuard(func(r *http.Request) bool { +// return subtle.ConstantTimeCompare( +// []byte(r.Header.Get("X-Ops-Token")), []byte(token)) == 1 +// }) +func WithObservabilityGuard(guard func(*http.Request) bool) AppOption { + return func(c *AppConfig) { c.ObservabilityGuard = guard } +} + +// WithInfoEndpoint registers /_/info. It is off by default because it lists +// the app's services, extensions and versions to whoever asks; pair it with +// WithObservabilityGuard anywhere beyond localhost. +func WithInfoEndpoint() AppOption { + return func(c *AppConfig) { c.EnableInfoEndpoint = true } +} + // WithExposeInternalErrors overrides whether 5xx responses carry the internal // error text, whatever the environment. See AppConfig.ExposeInternalErrors. func WithExposeInternalErrors(expose bool) AppOption { diff --git a/app_impl.go b/app_impl.go index 671af2c7..b1fee7c7 100644 --- a/app_impl.go +++ b/app_impl.go @@ -15,6 +15,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "syscall" "time" @@ -73,6 +74,12 @@ type app struct { // development one. It gates the defaults that trade safety for debugging // convenience: internal error text in 5xx bodies and health check detail. devEnvironment bool + + // unhealthyLogged is the timestamp (UnixNano) of the last health report + // whose unhealthy status was logged. The endpoint serves a cached report + // on every probe, so logging per request would repeat the same line at + // the probe rate; logging once per report keeps it to one per check. + unhealthyLogged atomic.Int64 } // newApp creates a new app instance. @@ -1204,14 +1211,44 @@ func (a *app) printStartupBanner() { // setupBuiltinEndpoints sets up built-in endpoints. func (a *app) setupBuiltinEndpoints() error { - // Info endpoint + // /_/info is opt-in: it lists the services, extensions and versions the + // app runs, which is a map for anyone probing it. + if !a.config.EnableInfoEndpoint { + return nil + } + if err := a.router.GET("/_/info", a.handleInfo); err != nil { return fmt.Errorf("failed to register info endpoint: %w", err) } + if a.config.ObservabilityGuard == nil && !a.devEnvironment { + a.logger.Warn("/_/info enabled without ObservabilityGuard: services, extensions and versions are unauthenticated", + F("environment", a.config.Environment), + ) + } + return nil } +// observabilityAllowed reports whether r may see the guarded observability +// endpoints. With no guard configured everyone may. +func (a *app) observabilityAllowed(r *http.Request) bool { + return a.config.ObservabilityGuard == nil || a.config.ObservabilityGuard(r) +} + +// healthDetailAllowed reports whether r gets the full health report, with +// each check's message and details, or only the statuses. A guard decides +// when there is one. Without one, only an explicit development environment +// shows details: check messages and details are free text that commonly +// carries connection strings and hostnames. +func (a *app) healthDetailAllowed(r *http.Request) bool { + if a.config.ObservabilityGuard != nil { + return a.config.ObservabilityGuard(r) + } + + return a.devEnvironment +} + // setupObservabilityEndpoints sets up observability endpoints. func (a *app) setupObservabilityEndpoints() error { // Setup metrics endpoint if enabled @@ -1317,6 +1354,13 @@ func (a *app) setupPprofEndpoints() error { // handleInfo handles the /_/info endpoint. func (a *app) handleInfo(ctx Context) error { + // 404 rather than 403, as for pprof, so the endpoint is not discoverable. + if !a.observabilityAllowed(ctx.Request()) { + http.NotFound(ctx.Response(), ctx.Request()) + + return nil + } + // Get service names from container services := a.container.Services() @@ -1612,16 +1656,33 @@ func (a *app) registerExtensionHealthChecks() { extRef := ext extName := ext.Name() + // The error text stays out of the result. Health results are served + // over HTTP and a driver error routinely names the host, the user and + // sometimes the whole DSN with its password. It goes to the log + // instead, once per distinct error rather than once per check round. + var lastErr atomic.Pointer[string] + checkName := "extension:" + extName if err := a.healthManager.RegisterFn(checkName, func(ctx context.Context) *HealthResult { if err := extRef.Health(ctx); err != nil { + msg := err.Error() + if prev := lastErr.Swap(&msg); prev == nil || *prev != msg { + a.logger.Warn("extension health check failed", + F("extension", extName), + F("error", msg), + ) + } + return &HealthResult{ Status: HealthStatusUnhealthy, Message: extName + " extension unhealthy", - Details: map[string]any{"error": err.Error()}, } } + if lastErr.Swap(nil) != nil { + a.logger.Info("extension health check recovered", F("extension", extName)) + } + return &HealthResult{ Status: HealthStatusHealthy, Message: extName + " extension healthy", @@ -2005,6 +2066,12 @@ func (a *app) handleMetrics(ctx Context) error { }) } + if !a.observabilityAllowed(ctx.Request()) { + http.NotFound(ctx.Response(), ctx.Request()) + + return nil + } + // If the collector implements PrometheusProvider, delegate to the real // promhttp handler so that content negotiation (OpenMetrics, compression, // etc.) is handled correctly by the Prometheus client library. @@ -2033,6 +2100,36 @@ func (a *app) handleMetrics(ctx Context) error { return nil } +// healthSummary is what /_/health shows a caller that may not see details: +// the overall status and the status of each check, nothing free-text. +type healthSummary struct { + Overall HealthStatus `json:"overall"` + Timestamp time.Time `json:"timestamp"` + Services map[string]healthCheckSummary `json:"services"` +} + +type healthCheckSummary struct { + Status HealthStatus `json:"status"` +} + +func summarizeHealthReport(report *HealthReport) healthSummary { + out := healthSummary{ + Overall: report.Overall, + Timestamp: report.Timestamp, + Services: make(map[string]healthCheckSummary, len(report.Services)), + } + + for name, res := range report.Services { + if res == nil { + continue + } + + out.Services[name] = healthCheckSummary{Status: res.Status} + } + + return out +} + // handleHealth handles the /_/health endpoint. func (a *app) handleHealth(ctx Context) error { if a.healthManager == nil { @@ -2052,12 +2149,17 @@ func (a *app) handleHealth(ctx Context) error { report, fresh := a.healthReport(ctx.Request().Context()) + var body any = report + if !a.healthDetailAllowed(ctx.Request()) { + body = summarizeHealthReport(report) + } + if !fresh { return ctx.JSON(http.StatusServiceUnavailable, map[string]any{ "status": "stale", "error": "health report is older than the staleness bound", "age": time.Since(report.Timestamp).String(), - "report": report, + "report": body, }) } @@ -2066,12 +2168,37 @@ func (a *app) handleHealth(ctx Context) error { if report.Overall == HealthStatusUnhealthy { statusCode = http.StatusServiceUnavailable - a.logger.Warn("health check reporting unhealthy status", - F("services", len(report.Services)), - ) + a.logUnhealthyReport(report) + } + + return ctx.JSON(statusCode, body) +} + +// logUnhealthyReport logs an unhealthy report once. Every probe is answered +// from the same cached report until the next check round, so logging per +// request would print the same line at whatever rate the probes arrive. +func (a *app) logUnhealthyReport(report *HealthReport) { + ts := report.Timestamp.UnixNano() + + prev := a.unhealthyLogged.Load() + if prev == ts || !a.unhealthyLogged.CompareAndSwap(prev, ts) { + return } - return ctx.JSON(statusCode, report) + failing := make([]string, 0, len(report.Services)) + + for name, res := range report.Services { + if res != nil && res.Status == HealthStatusUnhealthy { + failing = append(failing, name) + } + } + + slices.Sort(failing) + + a.logger.Warn("health check reporting unhealthy status", + F("services", len(report.Services)), + F("unhealthy", failing), + ) } // healthStalenessBound is how far behind the background check loop a cached diff --git a/app_observability_guard_test.go b/app_observability_guard_test.go new file mode 100644 index 00000000..18677c5c --- /dev/null +++ b/app_observability_guard_test.go @@ -0,0 +1,228 @@ +package forge + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/xraph/go-utils/log" + + forgelogger "github.com/xraph/forge/internal/logger" +) + +const leakyDSN = "postgres://app_rw:hunter2@10.0.3.17:5432/prod" + +// leakyExtension fails its health check with the kind of error a database +// driver really returns: host, user and the DSN with its password. +type leakyExtension struct{ *BaseExtension } + +func (l *leakyExtension) Health(context.Context) error { + return errors.New(`failed to connect to "host=10.0.3.17 user=app_rw database=prod": password authentication failed (dsn ` + leakyDSN + `)`) +} + +func newExposureApp(t *testing.T, env string, opts ...AppOption) (App, *log.TestLogger) { + t.Helper() + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + + logs := forgelogger.NewTestLogger().(*log.TestLogger) + + cfg := DefaultAppConfig() + cfg.Name = "prodapp" + cfg.Environment = env + cfg.HealthGracePeriod = time.Nanosecond + cfg.EnableConfigAutoDiscovery = false + cfg.Logger = logs + cfg.Extensions = []Extension{&leakyExtension{NewBaseExtension("database", "1.2.3", "db")}} + + a := New(append([]AppOption{WithConfig(cfg)}, opts...)...) + if err := a.Start(context.Background()); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = a.Stop(context.Background()) }) + + // Run a round the way the check loop does, so the cached report covers + // the extension check whatever Start already ran. + a.HealthManager().Check(context.Background()) + + return a, logs +} + +func obsGet(t *testing.T, a App, path string, hdr ...string) *httptest.ResponseRecorder { + t.Helper() + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil) + for i := 0; i+1 < len(hdr); i += 2 { + req.Header.Set(hdr[i], hdr[i+1]) + } + + w := httptest.NewRecorder() + a.Router().ServeHTTP(w, req) + + return w +} + +// In production with no guard, nothing an extension's health error says may +// reach a client, /_/info does not exist, and readiness still works. +func TestObservability_ProductionDefaultsDoNotLeak(t *testing.T) { + a, logs := newExposureApp(t, "production") + + for _, p := range []string{"/_/info", "/_/health", "/_/health/ready", "/_/health/live", "/_/metrics"} { + w := obsGet(t, a, p) + if strings.Contains(w.Body.String(), "hunter2") || strings.Contains(w.Body.String(), "10.0.3.17") { + t.Errorf("%s leaks the extension error: %s", p, w.Body.String()) + } + } + + if w := obsGet(t, a, "/_/info"); w.Code != http.StatusNotFound { + t.Errorf("/_/info = %d, want 404 because it is opt-in", w.Code) + } + + w := obsGet(t, a, "/_/health") + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("/_/health = %d, want 503; body %s", w.Code, w.Body.String()) + } + + var summary struct { + Overall string `json:"overall"` + Services map[string]map[string]any `json:"services"` + } + if err := json.Unmarshal(w.Body.Bytes(), &summary); err != nil { + t.Fatal(err) + } + + if summary.Overall != string(HealthStatusUnhealthy) { + t.Errorf("overall = %q, want unhealthy", summary.Overall) + } + + ext, ok := summary.Services["extension:database"] + if !ok { + t.Fatalf("summary has no extension:database check: %s", w.Body.String()) + } + + if len(ext) != 1 || ext["status"] != string(HealthStatusUnhealthy) { + t.Errorf("an unauthorized caller should see only the check status, got %v", ext) + } + + if w := obsGet(t, a, "/_/health/ready"); w.Code != http.StatusServiceUnavailable { + t.Errorf("/_/health/ready = %d, want 503 without any guard", w.Code) + } + + if w := obsGet(t, a, "/_/health/live"); w.Code != http.StatusOK { + t.Errorf("/_/health/live = %d, want 200 without any guard", w.Code) + } + + // The operator still gets the cause, in the log. + found := false + + for _, e := range logs.GetLogsByLevel("WARN") { + if e.Message != "extension health check failed" { + continue + } + + if v, _ := e.Field("error"); strings.Contains(v.(string), "password authentication failed") { + found = true + } + } + + if !found { + t.Error("the raw extension error is not in the log") + } +} + +// A guard decides who sees details. Denied callers get statuses only and +// 404s for info and metrics; allowed callers get the full report, which still +// carries no raw extension error. +func TestObservability_GuardControlsDetail(t *testing.T) { + guard := func(r *http.Request) bool { return r.Header.Get("X-Ops") == "yes" } + a, _ := newExposureApp(t, "production", WithObservabilityGuard(guard), WithInfoEndpoint()) + + if w := obsGet(t, a, "/_/info"); w.Code != http.StatusNotFound { + t.Errorf("denied /_/info = %d, want 404", w.Code) + } + + if w := obsGet(t, a, "/_/metrics"); w.Code != http.StatusNotFound { + t.Errorf("denied /_/metrics = %d, want 404", w.Code) + } + + if w := obsGet(t, a, "/_/info", "X-Ops", "yes"); w.Code != http.StatusOK { + t.Errorf("allowed /_/info = %d, want 200", w.Code) + } + + if w := obsGet(t, a, "/_/metrics", "X-Ops", "yes"); w.Code != http.StatusOK { + t.Errorf("allowed /_/metrics = %d, want 200", w.Code) + } + + denied := obsGet(t, a, "/_/health") + if strings.Contains(denied.Body.String(), "extension unhealthy") { + t.Errorf("denied /_/health carries check messages: %s", denied.Body.String()) + } + + allowed := obsGet(t, a, "/_/health", "X-Ops", "yes") + if !strings.Contains(allowed.Body.String(), "database extension unhealthy") { + t.Errorf("allowed /_/health should carry the full report: %s", allowed.Body.String()) + } + + if strings.Contains(allowed.Body.String(), "hunter2") { + t.Errorf("even an allowed /_/health must not carry the raw extension error: %s", allowed.Body.String()) + } + + // Probes never need the guard. + if w := obsGet(t, a, "/_/health/live"); w.Code != http.StatusOK { + t.Errorf("/_/health/live = %d, want 200", w.Code) + } +} + +// Without a guard an explicit development environment keeps the full report, +// so local debugging is unchanged. +func TestObservability_DevelopmentKeepsDetails(t *testing.T) { + a, _ := newExposureApp(t, "development", WithAppEnvironment("development")) + + w := obsGet(t, a, "/_/health") + if !strings.Contains(w.Body.String(), "database extension unhealthy") { + t.Errorf("development /_/health should carry check messages: %s", w.Body.String()) + } +} + +// Probes answer from one cached report, so an unhealthy app used to log a +// warning per probe. It now logs once per report. +func TestObservability_UnhealthyWarningIsNotPerRequest(t *testing.T) { + a, logs := newExposureApp(t, "production") + + for range 50 { + obsGet(t, a, "/_/health") + } + + n := 0 + + for _, e := range logs.GetLogsByLevel("WARN") { + if e.Message == "health check reporting unhealthy status" { + n++ + } + } + + if n != 1 { + t.Errorf("50 probes of one report logged %d unhealthy warnings, want 1", n) + } + + // The extension error itself is logged once, not once per check round. + a.HealthManager().Check(context.Background()) + a.HealthManager().Check(context.Background()) + + n = 0 + + for _, e := range logs.GetLogsByLevel("WARN") { + if e.Message == "extension health check failed" { + n++ + } + } + + if n != 1 { + t.Errorf("the same extension error was logged %d times, want 1", n) + } +} diff --git a/app_test.go b/app_test.go index c7fa8600..4f76a070 100644 --- a/app_test.go +++ b/app_test.go @@ -308,14 +308,15 @@ func (c *appTestController) Routes(r Router) error { }) } -// TestAppInfoEndpoint tests the /_/info endpoint. +// TestAppInfoEndpoint tests the /_/info endpoint, which is opt-in. func TestAppInfoEndpoint(t *testing.T) { app := NewApp(AppConfig{ - Name: "info-test", - Version: "1.0.0", - Description: "Test app", - Environment: "test", - Logger: logger.NewTestLogger(), + Name: "info-test", + Version: "1.0.0", + Description: "Test app", + Environment: "test", + Logger: logger.NewTestLogger(), + EnableInfoEndpoint: true, }) // Start app From eb9f7c076c56c22fe795a020a0faa6a6d5c02ab4 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:19:21 -0600 Subject: [PATCH 03/15] perf(metrics): share one render between scrapes and bound concurrent scrapes /_/metrics handed every scrape to promhttp with no limits, and each one walked every series and encoded all of them. With 200 routes that saw three statuses each, a scrape cost about 7 ms of CPU and 5.9 MB of allocation for a 1.7 MB body, so a handful of clients scraping in a loop could keep a core busy for free. The endpoint now goes through a scrape cache. Scrapes within MetricsScrapeCacheTTL (default 1s, WithMetricsScrapeCacheTTL, negative to disable) of each other are served from the last render, keyed by the negotiated exposition format and by whether the client accepts gzip, so the cache cannot grow with request headers. Renders run one at a time behind the cache lock, which makes a burst of concurrent scrapes cost one render. Scrapes that filter by name skip the cache and are capped at 4 in flight; more get a 503. The promhttp handler is built once and each render is cut off after 10s, Prometheus' default scrape timeout. BenchmarkMetricsScrape (Apple M5 Max), per scrape: routes=0 180 us, 103 KB, 901 allocs -> 1.1 us, 1.1 KB, 14 allocs routes=50 2.1 ms, 1.6 MB, 25771 -> 1.0 us, 1.1 KB, 14 allocs routes=200 6.9 ms, 5.9 MB, 100042 -> 0.8 us, 1.1 KB, 14 allocs A scrape that misses the cache costs what it did before; at most one does per TTL and format. --- app.go | 13 ++ app_impl.go | 30 ++- internal/metrics/exporters/prometheus.go | 16 +- internal/metrics/exporters/scrape_cache.go | 207 ++++++++++++++++++ .../metrics/exporters/scrape_cache_test.go | 175 +++++++++++++++ metrics_scrape_bench_test.go | 74 +++++++ metrics_scrape_cache_test.go | 57 +++++ 7 files changed, 569 insertions(+), 3 deletions(-) create mode 100644 internal/metrics/exporters/scrape_cache.go create mode 100644 internal/metrics/exporters/scrape_cache_test.go create mode 100644 metrics_scrape_bench_test.go create mode 100644 metrics_scrape_cache_test.go diff --git a/app.go b/app.go index 5072a835..4195b3d4 100644 --- a/app.go +++ b/app.go @@ -142,6 +142,13 @@ type AppConfig struct { // EnableInfoEndpoint registers /_/info, which lists the services, // extensions, versions and Go version the app runs. Default: false. EnableInfoEndpoint bool + + // MetricsScrapeCacheTTL is how long a rendered /_/metrics response is + // reused. Concurrent scrapes inside the window share one render, so a + // burst of scrapers costs one gather and one encode. Zero means the + // default of 1s; negative disables the cache. + MetricsScrapeCacheTTL time.Duration + // ExposeInternalErrors decides whether 5xx responses carry the internal // error text. Nil means it follows Environment: only an explicitly set // development, dev, local or test environment exposes it. An unset or @@ -535,6 +542,12 @@ func WithInfoEndpoint() AppOption { return func(c *AppConfig) { c.EnableInfoEndpoint = true } } +// WithMetricsScrapeCacheTTL sets how long a rendered /_/metrics response is +// reused. See AppConfig.MetricsScrapeCacheTTL. +func WithMetricsScrapeCacheTTL(ttl time.Duration) AppOption { + return func(c *AppConfig) { c.MetricsScrapeCacheTTL = ttl } +} + // WithExposeInternalErrors overrides whether 5xx responses carry the internal // error text, whatever the environment. See AppConfig.ExposeInternalErrors. func WithExposeInternalErrors(expose bool) AppOption { diff --git a/app_impl.go b/app_impl.go index b1fee7c7..f31e3a7c 100644 --- a/app_impl.go +++ b/app_impl.go @@ -80,6 +80,11 @@ type app struct { // on every probe, so logging per request would repeat the same line at // the probe rate; logging once per report keeps it to one per check. unhealthyLogged atomic.Int64 + + // metricsHandler serves /_/metrics through the scrape cache. Built on + // first use, since the collector is only final once Start has run. + metricsOnce sync.Once + metricsHandler http.Handler } // newApp creates a new app instance. @@ -2076,7 +2081,7 @@ func (a *app) handleMetrics(ctx Context) error { // promhttp handler so that content negotiation (OpenMetrics, compression, // etc.) is handled correctly by the Prometheus client library. if p, ok := a.metrics.(shared.PrometheusProvider); ok { - p.PrometheusHandler().ServeHTTP(ctx.Response(), ctx.Request()) + a.scrapeHandler(p).ServeHTTP(ctx.Response(), ctx.Request()) return nil } @@ -2100,6 +2105,29 @@ func (a *app) handleMetrics(ctx Context) error { return nil } +// defaultMetricsScrapeCacheTTL is how long a rendered scrape is reused when +// AppConfig.MetricsScrapeCacheTTL is left at zero. A second is far below any +// sensible scrape interval, so a single scraper always sees fresh data, while +// a burst of scrapers (several Prometheus replicas, a dashboard, a script in +// a loop) shares one render. +const defaultMetricsScrapeCacheTTL = time.Second + +// scrapeHandler returns the /_/metrics handler, wrapped in the scrape cache. +// The bridge is fixed once the collector is built, so the wrapper is built +// once and reused. +func (a *app) scrapeHandler(p shared.PrometheusProvider) http.Handler { + a.metricsOnce.Do(func() { + ttl := a.config.MetricsScrapeCacheTTL + if ttl == 0 { + ttl = defaultMetricsScrapeCacheTTL + } + + a.metricsHandler = exporters.NewScrapeCache(p.PrometheusHandler(), ttl) + }) + + return a.metricsHandler +} + // healthSummary is what /_/health shows a caller that may not see details: // the overall status and the status of each check, nothing free-text. type healthSummary struct { diff --git a/internal/metrics/exporters/prometheus.go b/internal/metrics/exporters/prometheus.go index 16f911d0..ae769c7c 100644 --- a/internal/metrics/exporters/prometheus.go +++ b/internal/metrics/exporters/prometheus.go @@ -42,6 +42,9 @@ func DefaultPrometheusConfig() PrometheusConfig { type PrometheusBridge struct { registry *prometheus.Registry collector *forgeCollector + + handlerOnce sync.Once + handler http.Handler } // NewPrometheusBridge builds a bridge that reads `snapshot` fresh on each scrape. @@ -73,9 +76,18 @@ func newBridge(fc *forgeCollector, cfg PrometheusConfig) *PrometheusBridge { return &PrometheusBridge{registry: reg, collector: fc} } -// Handler returns an HTTP handler that serves the registry on scrape. +// Handler returns an HTTP handler that serves the registry on scrape. Each +// scrape is cut off after ScrapeTimeout. Wrap it in NewScrapeCache to share +// renders between scrapes and bound how many run at once. func (b *PrometheusBridge) Handler() http.Handler { - return promhttp.HandlerFor(b.registry, promhttp.HandlerOpts{EnableOpenMetrics: true}) + b.handlerOnce.Do(func() { + b.handler = promhttp.HandlerFor(b.registry, promhttp.HandlerOpts{ + EnableOpenMetrics: true, + Timeout: ScrapeTimeout, + }) + }) + + return b.handler } // GatherText gathers the registry and encodes it in Prometheus text format. diff --git a/internal/metrics/exporters/scrape_cache.go b/internal/metrics/exporters/scrape_cache.go new file mode 100644 index 00000000..bc7bb394 --- /dev/null +++ b/internal/metrics/exporters/scrape_cache.go @@ -0,0 +1,207 @@ +package exporters + +import ( + "bytes" + "net/http" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/prometheus/common/expfmt" +) + +// Scrape handler limits. A scrape walks every series and encodes all of them, +// which on an app with a few hundred routes is milliseconds of CPU and +// megabytes of garbage, so an unbounded number of them running at once is a +// cheap way to load the process. +const ( + // ScrapeMaxRequestsInFlight caps the scrapes NewScrapeCache lets past it + // uncached (the ones filtering by name). Further ones get a 503 and the + // scraper retries on its next interval. Cached scrapes need no cap: they + // render one at a time. + ScrapeMaxRequestsInFlight = 4 + + // ScrapeTimeout bounds one render. It matches Prometheus' default scrape + // timeout, after which the scraper has given up anyway. + ScrapeTimeout = 10 * time.Second +) + +// scrapeKey identifies one rendering of the registry. A scrape's bytes depend +// only on the negotiated exposition format and on whether the body is +// gzipped, and both come from a small fixed set, so the cache cannot grow +// with whatever headers a client sends. +type scrapeKey struct { + format expfmt.Format + gzip bool +} + +type scrapeEntry struct { + at time.Time + status int + header http.Header + body []byte +} + +// scrapeCache serves repeated scrapes from the last rendering for ttl. +type scrapeCache struct { + next http.Handler + ttl time.Duration + now func() time.Time + + // mu guards entries and is held across a render. Holding it is what + // makes a burst of scrapes cost one render: the first one renders and + // the rest wait for it and then read its result instead of each walking + // the registry again. + mu sync.Mutex + entries map[scrapeKey]*scrapeEntry + + // bypass bounds the scrapes that skip the cache. + bypass chan struct{} +} + +// NewScrapeCache wraps a Prometheus scrape handler, such as the one +// PrometheusBridge.Handler returns, so that scrapes within ttl of each other +// share one rendering. Scrapes that filter by name (any query string) and +// methods other than GET and HEAD bypass the cache, at most +// ScrapeMaxRequestsInFlight at a time. +// +// A ttl of zero or less turns caching off; the concurrency cap still applies. +func NewScrapeCache(next http.Handler, ttl time.Duration) http.Handler { + return &scrapeCache{ + next: next, + ttl: ttl, + now: time.Now, + entries: make(map[scrapeKey]*scrapeEntry, 2), + bypass: make(chan struct{}, ScrapeMaxRequestsInFlight), + } +} + +func (c *scrapeCache) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if c.ttl <= 0 || (r.Method != http.MethodGet && r.Method != http.MethodHead) || (r.URL != nil && r.URL.RawQuery != "") { + select { + case c.bypass <- struct{}{}: + defer func() { <-c.bypass }() + default: + http.Error(w, "too many concurrent scrapes, try again later", http.StatusServiceUnavailable) + + return + } + + c.next.ServeHTTP(w, r) + + return + } + + key := scrapeKey{ + format: expfmt.NegotiateIncludingOpenMetrics(r.Header), + gzip: acceptsGzip(r.Header.Get("Accept-Encoding")), + } + + c.mu.Lock() + + e := c.entries[key] + if e == nil || c.now().Sub(e.at) >= c.ttl { + e = c.render(r, key) + + // Only a good render is worth repeating. An error or a 503 from the + // in-flight limit goes to this caller alone. + if e.status == http.StatusOK { + c.entries[key] = e + } else { + delete(c.entries, key) + } + } + + c.mu.Unlock() + + h := w.Header() + for k, v := range e.header { + h[k] = slices.Clone(v) + } + + h.Set("Content-Length", strconv.Itoa(len(e.body))) + w.WriteHeader(e.status) + + if r.Method != http.MethodHead { + _, _ = w.Write(e.body) + } +} + +// render runs the wrapped handler into memory. The request is pinned to the +// encoding the key names, so what is stored matches the key whatever else +// the original Accept-Encoding listed. +func (c *scrapeCache) render(r *http.Request, key scrapeKey) *scrapeEntry { + req := r.Clone(r.Context()) + req.Method = http.MethodGet + + if key.gzip { + req.Header.Set("Accept-Encoding", "gzip") + } else { + req.Header.Set("Accept-Encoding", "identity") + } + + rec := &bufferedResponse{header: make(http.Header)} + c.next.ServeHTTP(rec, req) + + status := rec.status + if status == 0 { + status = http.StatusOK + } + + // Drop anything hop-specific; Content-Length is recomputed per write. + rec.header.Del("Content-Length") + + return &scrapeEntry{at: c.now(), status: status, header: rec.header, body: rec.body.Bytes()} +} + +// acceptsGzip reports whether an Accept-Encoding value allows gzip, either by +// name or through a wildcard, without a zero quality. +func acceptsGzip(header string) bool { + if header == "" { + return false + } + + for part := range strings.SplitSeq(header, ",") { + name, params, _ := strings.Cut(strings.TrimSpace(part), ";") + name = strings.ToLower(strings.TrimSpace(name)) + + if name != "gzip" && name != "*" { + continue + } + + if q, ok := strings.CutPrefix(strings.ReplaceAll(params, " ", ""), "q="); ok { + if v, err := strconv.ParseFloat(q, 64); err == nil && v == 0 { + continue + } + } + + return true + } + + return false +} + +// bufferedResponse captures a handler's response in memory. +type bufferedResponse struct { + header http.Header + status int + body bytes.Buffer +} + +func (b *bufferedResponse) Header() http.Header { return b.header } + +func (b *bufferedResponse) WriteHeader(status int) { + if b.status == 0 { + b.status = status + } +} + +func (b *bufferedResponse) Write(p []byte) (int, error) { + if b.status == 0 { + b.status = http.StatusOK + } + + return b.body.Write(p) +} diff --git a/internal/metrics/exporters/scrape_cache_test.go b/internal/metrics/exporters/scrape_cache_test.go new file mode 100644 index 00000000..6405d838 --- /dev/null +++ b/internal/metrics/exporters/scrape_cache_test.go @@ -0,0 +1,175 @@ +package exporters + +import ( + "compress/gzip" + "io" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" +) + +// countingScrape stands in for promhttp: it counts renders and honours the +// Accept-Encoding the cache pins. +type countingScrape struct { + renders atomic.Int64 + delay time.Duration + block chan struct{} +} + +func (c *countingScrape) ServeHTTP(w http.ResponseWriter, r *http.Request) { + c.renders.Add(1) + + if c.delay > 0 { + time.Sleep(c.delay) + } + + if c.block != nil { + <-c.block + } + + w.Header().Set("Content-Type", "text/plain; version=0.0.4") + + body := "up 1\n" + + if r.Header.Get("Accept-Encoding") == "gzip" { + w.Header().Set("Content-Encoding", "gzip") + + gz := gzip.NewWriter(w) + _, _ = io.WriteString(gz, body) + _ = gz.Close() + + return + } + + _, _ = io.WriteString(w, body) +} + +func TestScrapeCache_ConcurrentScrapesShareOneRender(t *testing.T) { + next := &countingScrape{delay: 20 * time.Millisecond} + h := NewScrapeCache(next, time.Second) + + var wg sync.WaitGroup + + for range 50 { + wg.Go(func() { + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/_/metrics", nil)) + + if rec.Code != http.StatusOK || rec.Body.String() != "up 1\n" { + t.Errorf("got %d %q", rec.Code, rec.Body.String()) + } + }) + } + + wg.Wait() + + if n := next.renders.Load(); n != 1 { + t.Errorf("50 concurrent scrapes rendered %d times, want 1", n) + } +} + +func TestScrapeCache_ExpiresAndKeysByEncoding(t *testing.T) { + next := &countingScrape{} + c := NewScrapeCache(next, time.Second).(*scrapeCache) + + now := time.Unix(1000, 0) + c.now = func() time.Time { return now } + + get := func(encoding string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/_/metrics", nil) + if encoding != "" { + req.Header.Set("Accept-Encoding", encoding) + } + + rec := httptest.NewRecorder() + c.ServeHTTP(rec, req) + + return rec + } + + get("") + get("") + + if n := next.renders.Load(); n != 1 { + t.Fatalf("two scrapes in one window rendered %d times", n) + } + + gz := get("gzip, deflate") + if gz.Header().Get("Content-Encoding") != "gzip" { + t.Fatalf("gzip scrape got Content-Encoding %q", gz.Header().Get("Content-Encoding")) + } + + zr, err := gzip.NewReader(gz.Body) + if err != nil { + t.Fatal(err) + } + + if b, _ := io.ReadAll(zr); string(b) != "up 1\n" { + t.Fatalf("gzip body = %q", b) + } + + if plain := get("gzip;q=0"); plain.Header().Get("Content-Encoding") != "" { + t.Fatal("q=0 must not get gzip") + } + + if n := next.renders.Load(); n != 2 { + t.Fatalf("plain and gzip should render once each, rendered %d", n) + } + + now = now.Add(time.Second) + get("") + + if n := next.renders.Load(); n != 3 { + t.Fatalf("an expired entry should render again, rendered %d", n) + } +} + +func TestScrapeCache_UncachedScrapesAreCapped(t *testing.T) { + next := &countingScrape{block: make(chan struct{})} + h := NewScrapeCache(next, time.Second) + + var wg sync.WaitGroup + + for range ScrapeMaxRequestsInFlight { + wg.Go(func() { + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/_/metrics?name[]=up", nil)) + }) + } + + deadline := time.Now().Add(5 * time.Second) + for next.renders.Load() < ScrapeMaxRequestsInFlight && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/_/metrics?name[]=up", nil)) + + if rec.Code != http.StatusServiceUnavailable { + t.Errorf("scrape over the cap = %d, want 503", rec.Code) + } + + close(next.block) + wg.Wait() +} + +func TestAcceptsGzip(t *testing.T) { + for header, want := range map[string]bool{ + "": false, + "gzip": true, + "deflate, gzip": true, + "GZIP;q=0.5": true, + "gzip;q=0": false, + "gzip; q=0": false, + "*": true, + "identity": false, + "br, zstd": false, + "x-gzip-ish, other": false, + } { + if got := acceptsGzip(header); got != want { + t.Errorf("acceptsGzip(%q) = %v, want %v", header, got, want) + } + } +} diff --git a/metrics_scrape_bench_test.go b/metrics_scrape_bench_test.go new file mode 100644 index 00000000..15eb1c5a --- /dev/null +++ b/metrics_scrape_bench_test.go @@ -0,0 +1,74 @@ +package forge + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" +) + +// BenchmarkMetricsScrape measures a /_/metrics scrape through the router on an +// app that has served traffic on many routes, so the HTTP series dominate. +// Each route saw three statuses, which is what makes a real scrape large. +func BenchmarkMetricsScrape(b *testing.B) { + for _, routes := range []int{0, 50, 200} { + b.Run(fmt.Sprintf("routes=%d", routes), func(b *testing.B) { + b.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + + cfg := DefaultAppConfig() + cfg.EnableConfigAutoDiscovery = false + cfg.Logger = NewNoopLogger() + a := New(WithConfig(cfg)) + + for i := range routes { + _ = a.Router().GET(fmt.Sprintf("/r%d/:id", i), func(c Context) error { + switch c.Param("id") { + case "e": + return c.String(http.StatusInternalServerError, "x") + case "n": + return c.String(http.StatusNotFound, "x") + default: + return c.String(http.StatusOK, "ok") + } + }) + } + + if err := a.Start(context.Background()); err != nil { + b.Fatal(err) + } + + defer func() { _ = a.Stop(context.Background()) }() + + h := a.Router() + + for i := range routes { + for _, id := range []string{"1", "e", "n"} { + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, fmt.Sprintf("/r%d/%s", i, id), nil)) + } + } + + req := httptest.NewRequest(http.MethodGet, "/_/metrics", nil) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, req) + + if rr.Code != http.StatusOK { + b.Fatalf("scrape status %d", rr.Code) + } + + b.ReportAllocs() + + for b.Loop() { + h.ServeHTTP(&discardResponseWriter{h: http.Header{}}, req) + } + + b.ReportMetric(float64(rr.Body.Len()), "resp_bytes") + }) + } +} + +type discardResponseWriter struct{ h http.Header } + +func (d *discardResponseWriter) Header() http.Header { return d.h } +func (d *discardResponseWriter) Write(p []byte) (int, error) { return len(p), nil } +func (d *discardResponseWriter) WriteHeader(int) {} diff --git a/metrics_scrape_cache_test.go b/metrics_scrape_cache_test.go new file mode 100644 index 00000000..1489c979 --- /dev/null +++ b/metrics_scrape_cache_test.go @@ -0,0 +1,57 @@ +package forge + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func scrapeThroughRouter(t *testing.T, a App) string { + t.Helper() + + w := httptest.NewRecorder() + a.Router().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/_/metrics", nil)) + + if w.Code != http.StatusOK { + t.Fatalf("/_/metrics = %d", w.Code) + } + + return w.Body.String() +} + +// /_/metrics reuses a render for MetricsScrapeCacheTTL, and a negative TTL +// renders every scrape afresh. +func TestMetricsEndpoint_ScrapeCacheTTL(t *testing.T) { + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + + for _, tc := range []struct { + name string + ttl time.Duration + cached bool + }{ + // A minute rather than the default second, so the test cannot race + // the window. + {"cached", time.Minute, true}, + {"disabled", -1, false}, + } { + t.Run(tc.name, func(t *testing.T) { + a := New(WithAppEnvironment("test"), WithMetricsScrapeCacheTTL(tc.ttl), WithAppLogger(NewNoopLogger())) + if err := a.Start(context.Background()); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = a.Stop(context.Background()) }) + + scrapeThroughRouter(t, a) + a.Metrics().Counter("scrape_cache_probe_total").Inc() + + seen := strings.Contains(scrapeThroughRouter(t, a), "scrape_cache_probe_total") + if seen == tc.cached { + t.Errorf("second scrape saw the new series = %v, want %v", seen, !tc.cached) + } + }) + } +} From cf000c58d55c8257600c8bb2a039904890f04991 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:20:17 -0600 Subject: [PATCH 04/15] fix(http): put a write deadline on every response that does not stream Run served with WriteTimeout 0 so that SSE, WebSocket and gRPC streams would not be cut, and per-route timeouts default to 0 as well, so nothing bounded a write. A client that requested a large body and never read it pinned the handler goroutine and the connection indefinitely; twenty such clients pinned twenty handlers. Run now serves the router behind a per-request write deadline set with http.ResponseController, HTTPWriteTimeout (WithHTTPWriteTimeout), 60s by default and disabled when negative. Streams are exempt in two ways: - by request headers, before routing: an Upgrade or Connection: upgrade, an extended CONNECT, Accept: text/event-stream, or a gRPC content type; - by route kind, after routing: an outer middleware that shares the tracing and metrics route-match holder lifts the deadline when the router stamps a stream route (SSE, WebSocket, WebTransport), so an event stream opened without the Accept header is not cut either. A handler that streams on an ordinary route can lift the deadline itself with http.NewResponseController(w).SetWriteDeadline(time.Time{}). The router is untouched; the deadline only applies when the app serves through Run, not to a.Router() mounted in a server of the caller's own. --- app.go | 15 +++ app_impl.go | 125 +++++++++++++++++- app_write_deadline_test.go | 257 +++++++++++++++++++++++++++++++++++++ 3 files changed, 390 insertions(+), 7 deletions(-) create mode 100644 app_write_deadline_test.go diff --git a/app.go b/app.go index 4195b3d4..d04c8243 100644 --- a/app.go +++ b/app.go @@ -122,6 +122,14 @@ type AppConfig struct { // "*.example.com", or "*" to allow any origin. WebSocketOrigins []string + // HTTPWriteTimeout bounds how long the server spends writing one response. + // A client that requests a large body and never reads it otherwise pins a + // handler goroutine and a connection forever. Responses that stream (a + // WebSocket or other Upgrade, an SSE request, gRPC, or any route the router + // classifies as a stream) are exempt, so long-lived connections keep + // working. Zero means the default of 60s; negative disables the deadline. + HTTPWriteTimeout time.Duration + // Shutdown ShutdownTimeout time.Duration // Default: 30s ShutdownSignals []os.Signal // Default: SIGINT, SIGTERM @@ -523,6 +531,13 @@ func WithWebSocketOrigins(origins ...string) AppOption { } } +// WithHTTPWriteTimeout bounds how long the server spends writing one +// non-streaming response. See AppConfig.HTTPWriteTimeout. Pass a negative +// value to disable it. +func WithHTTPWriteTimeout(timeout time.Duration) AppOption { + return func(c *AppConfig) { c.HTTPWriteTimeout = timeout } +} + // WithObservabilityGuard restricts the detailed observability endpoints. The // guard runs on every request to /_/health, /_/info and /_/metrics; see // AppConfig.ObservabilityGuard for what a denied caller sees. diff --git a/app_impl.go b/app_impl.go index f31e3a7c..eccd9332 100644 --- a/app_impl.go +++ b/app_impl.go @@ -394,6 +394,12 @@ func newApp(config AppConfig) *app { internalrouter.UseOuterMiddleware(router, telemetry.RouteMatchMiddleware(tracing.Settings().ExcludePaths)) } + // Innermost of the outer middleware, so it shares the route-match holder + // tracing or HTTP metrics installed: when the router classifies a route + // as a stream, the write deadline Run puts on the response is lifted + // before the stream starts. Without Run's wrapper it does nothing. + internalrouter.UseOuterMiddleware(router, liftWriteDeadlineOnStreams) + // Register core services with DI - Both key-based (legacy) and type-based (new pattern) // Key-based registration (backward compatibility) @@ -1070,17 +1076,16 @@ func (a *app) Run() error { } // Create HTTP server. - // WriteTimeout is set to 0 (disabled) because SSE, WebSocket, and gRPC - // streaming handlers need indefinite write durations. A server-wide - // WriteTimeout kills ALL long-lived connections after the deadline, - // making streaming impossible. Regular REST handlers are protected by - // per-route timeouts applied at the router level instead. + // The server-wide WriteTimeout stays off because it would also cut SSE, + // WebSocket and gRPC streams. The per-request write deadline in + // serverHandler takes its place for everything that does not stream, so + // a client that never reads its response cannot pin a handler forever. a.httpServer = &http.Server{ Addr: a.config.HTTPAddress, - Handler: a.router, + Handler: a.serverHandler(), ReadTimeout: a.config.HTTPTimeout, ReadHeaderTimeout: 10 * time.Second, - WriteTimeout: 0, // disabled — streaming requires indefinite writes + WriteTimeout: 0, // see serverHandler IdleTimeout: a.config.HTTPTimeout * 2, } @@ -1126,6 +1131,112 @@ func (a *app) Run() error { return a.gracefulShutdown() } +// defaultHTTPWriteTimeout is the write deadline for a non-streaming response +// when AppConfig.HTTPWriteTimeout is left at zero. +const defaultHTTPWriteTimeout = 60 * time.Second + +// serverHandler is the root handler Run serves: the router behind a write +// deadline for every response that does not stream. +func (a *app) serverHandler() http.Handler { + timeout := a.config.HTTPWriteTimeout + if timeout == 0 { + timeout = defaultHTTPWriteTimeout + } + + return withWriteDeadline(a.router, timeout) +} + +// writeDeadlineKey carries a request's *writeDeadline on its context. +type writeDeadlineKey struct{} + +// writeDeadline lets middleware deeper in the chain lift the deadline once it +// learns the request is a stream. +type writeDeadline struct { + rc *http.ResponseController +} + +func (d *writeDeadline) lift() { + _ = d.rc.SetWriteDeadline(time.Time{}) +} + +// withWriteDeadline puts a write deadline of timeout on every response that +// does not stream. net/http only has a server-wide WriteTimeout, which would +// also cut every SSE, WebSocket and gRPC stream, so the deadline is set per +// request through http.ResponseController instead. +// +// net/http clears the connection's write deadline after each response, so a +// deadline never carries over to the next request on a keep-alive connection. +// +// Requests are recognised as streams from their headers here, and from the +// matched route's kind by liftWriteDeadlineOnStreams. A handler that streams +// on an ordinary route can lift the deadline itself with +// http.NewResponseController(w).SetWriteDeadline(time.Time{}). +func withWriteDeadline(next http.Handler, timeout time.Duration) http.Handler { + if timeout <= 0 { + return next + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if isStreamingRequest(r) { + next.ServeHTTP(w, r) + + return + } + + rc := http.NewResponseController(w) + _ = rc.SetWriteDeadline(time.Now().Add(timeout)) + + ctx := context.WithValue(r.Context(), writeDeadlineKey{}, &writeDeadline{rc: rc}) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +// isStreamingRequest reports whether the request asks for a connection that +// outlives an ordinary response: a protocol upgrade (WebSocket), an extended +// CONNECT (WebSocket or WebTransport over HTTP/2 and HTTP/3), an event +// stream, or gRPC. +func isStreamingRequest(r *http.Request) bool { + if r.Method == http.MethodConnect || r.Header.Get("Upgrade") != "" { + return true + } + + if strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade") { + return true + } + + if strings.Contains(r.Header.Get("Accept"), "text/event-stream") { + return true + } + + return strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") +} + +// liftWriteDeadlineOnStreams lifts the write deadline when the router matches +// a stream route (SSE, WebSocket, WebTransport), whatever headers the client +// sent: a client is free to open an event stream without Accept: +// text/event-stream. It runs inside the tracing and metrics middleware so it +// shares their route-match holder, and the router stamps the route's kind on +// that holder before any of the route's own code runs. +func liftWriteDeadlineOnStreams(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + d, ok := r.Context().Value(writeDeadlineKey{}).(*writeDeadline) + if !ok { + next.ServeHTTP(w, r) + + return + } + + ctx, m := shared.EnsureRouteMatch(r.Context()) + m.OnMatched(func(string) { + if m.Kind.LongLived() { + d.lift() + } + }) + + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + // gracefulShutdown performs a graceful shutdown. func (a *app) gracefulShutdown() error { ctx, cancel := context.WithTimeout(context.Background(), a.config.ShutdownTimeout) diff --git a/app_write_deadline_test.go b/app_write_deadline_test.go new file mode 100644 index 00000000..733c35dc --- /dev/null +++ b/app_write_deadline_test.go @@ -0,0 +1,257 @@ +package forge + +import ( + "bufio" + "bytes" + "context" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +// newDeadlineServer serves the app the way Run does, through serverHandler. +func newDeadlineServer(t *testing.T, a *app) *httptest.Server { + t.Helper() + + srv := httptest.NewUnstartedServer(a.serverHandler()) + srv.Start() + t.Cleanup(srv.Close) + + return srv +} + +func newDeadlineApp(t *testing.T, timeout time.Duration) *app { + t.Helper() + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + + cfg := DefaultAppConfig() + cfg.EnableConfigAutoDiscovery = false + cfg.Logger = NewNoopLogger() + cfg.HTTPWriteTimeout = timeout + + return New(WithConfig(cfg)).(*app) +} + +// A client that asks for a large body and never reads it used to pin the +// handler and the connection forever. The write deadline now cuts it off. +func TestWriteDeadline_SlowReaderIsCutOff(t *testing.T) { + a := newDeadlineApp(t, 500*time.Millisecond) + + var entered, returned atomic.Int32 + + body := bytes.Repeat([]byte("x"), 32<<20) + + _ = a.Router().GET("/big", func(c Context) error { + entered.Add(1) + defer returned.Add(1) + + c.Response().Header().Set("Content-Type", "application/octet-stream") + _, err := c.Response().Write(body) + + return err + }) + + srv := newDeadlineServer(t, a) + addr := strings.TrimPrefix(srv.URL, "http://") + + const clients = 5 + + for range clients { + conn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = conn.Close() }) + + _ = conn.(*net.TCPConn).SetReadBuffer(4096) + _, _ = fmt.Fprintf(conn, "GET /big HTTP/1.1\r\nHost: x\r\n\r\n") + // Never read. + } + + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + if entered.Load() == clients && returned.Load() == clients { + return + } + + time.Sleep(20 * time.Millisecond) + } + + t.Fatalf("handlers entered=%d returned=%d: slow readers still pin handlers past the write deadline", + entered.Load(), returned.Load()) +} + +// An SSE stream outlives the write deadline, both when the client says it +// wants an event stream and when it does not (the route kind decides). +func TestWriteDeadline_SSEKeepsStreaming(t *testing.T) { + a := newDeadlineApp(t, 200*time.Millisecond) + + _ = a.Router().SSE("/events", func(c Context) error { + for i := range 8 { + if err := c.WriteSSE("tick", fmt.Sprint(i)); err != nil { + return err + } + + time.Sleep(100 * time.Millisecond) + } + + return nil + }) + + srv := newDeadlineServer(t, a) + + for _, accept := range []string{"text/event-stream", ""} { + t.Run("accept="+accept, func(t *testing.T) { + req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL+"/events", nil) + if accept != "" { + req.Header.Set("Accept", accept) + } + + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + events := 0 + + sc := bufio.NewScanner(resp.Body) + for sc.Scan() { + if strings.HasPrefix(sc.Text(), "event: tick") { + events++ + } + } + + // Eight events over 800ms, four times the write deadline. + if events != 8 { + t.Errorf("got %d of 8 events (scan err %v): the stream was cut by the write deadline", events, sc.Err()) + } + }) + } +} + +// A plain handler that streams with Accept: text/event-stream is exempt too, +// including on a keep-alive connection whose previous request had a deadline +// that has since expired. +func TestWriteDeadline_StreamAfterOrdinaryRequestOnSameConnection(t *testing.T) { + a := newDeadlineApp(t, 200*time.Millisecond) + + _ = a.Router().GET("/ping", func(c Context) error { return c.String(http.StatusOK, "pong") }) + _ = a.Router().GET("/manual", func(c Context) error { + w := c.Response() + w.Header().Set("Content-Type", "text/event-stream") + + for i := range 6 { + _, _ = fmt.Fprintf(w, "data: %d\n\n", i) + _ = http.NewResponseController(w).Flush() + + time.Sleep(100 * time.Millisecond) + } + + return nil + }) + + srv := newDeadlineServer(t, a) + client := srv.Client() + + resp, err := client.Get(srv.URL + "/ping") + if err != nil { + t.Fatal(err) + } + + _, _ = bufio.NewReader(resp.Body).ReadString('\n') + _ = resp.Body.Close() + + // Let the first request's deadline expire on the idle connection. + time.Sleep(300 * time.Millisecond) + + req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL+"/manual", nil) + req.Header.Set("Accept", "text/event-stream") + + resp, err = client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + n := 0 + + sc := bufio.NewScanner(resp.Body) + for sc.Scan() { + if strings.HasPrefix(sc.Text(), "data:") { + n++ + } + } + + if n != 6 { + t.Errorf("got %d of 6 events: the stream inherited a write deadline", n) + } +} + +// A WebSocket connection keeps working well past the write deadline. +func TestWriteDeadline_WebSocketKeepsWorking(t *testing.T) { + a := newDeadlineApp(t, 200*time.Millisecond) + + _ = a.Router().WebSocket("/ws", func(c Context, conn Connection) error { + for { + msg, err := conn.Read() + if err != nil { + return nil //nolint:nilerr // the client hung up + } + + if err := conn.Write(msg); err != nil { + return err + } + } + }) + + srv := newDeadlineServer(t, a) + url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws" + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + // Same-origin, so the router's Origin check accepts it. + d := ws.Dialer{Header: ws.HandshakeHeaderHTTP(http.Header{"Origin": {srv.URL}})} + + conn, _, _, err := d.Dial(ctx, url) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + for i := range 4 { + time.Sleep(150 * time.Millisecond) + + want := fmt.Sprintf("hello %d", i) + if err := wsutil.WriteClientText(conn, []byte(want)); err != nil { + t.Fatalf("write %d: %v", i, err) + } + + got, err := wsutil.ReadServerText(conn) + if err != nil { + t.Fatalf("read %d after %v: %v", i, time.Duration(i+1)*150*time.Millisecond, err) + } + + if string(got) != want { + t.Fatalf("echo %d = %q, want %q", i, got, want) + } + } +} + +// A negative timeout turns the deadline off and serves the router directly. +func TestWriteDeadline_NegativeDisables(t *testing.T) { + a := newDeadlineApp(t, -1) + if a.serverHandler() != http.Handler(a.router) { + t.Fatal("a negative HTTPWriteTimeout should serve the router unwrapped") + } +} From 17495ae447ed9103e124927764ee3bf172b39784 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:20:23 -0600 Subject: [PATCH 05/15] fix(http): drop a WriteHeader that follows a failed body write When a body write fails, the connection is already broken: the client went away or a write deadline fired. The handler then returns the write error and the error handler tries to send a 500, which reached net/http as a second WriteHeader and was logged as "superfluous response.WriteHeader call" against beforewrite.go, once per failed request, for what is not a handler bug. The wrapper now remembers a failed Write or ReadFrom and drops a WriteHeader after it. A second WriteHeader without a failed write in between still goes through, so net/http keeps reporting real double writes. --- internal/shared/beforewrite.go | 57 ++++++++++++++++--- .../shared/beforewrite_failed_write_test.go | 56 ++++++++++++++++++ 2 files changed, 104 insertions(+), 9 deletions(-) create mode 100644 internal/shared/beforewrite_failed_write_test.go diff --git a/internal/shared/beforewrite.go b/internal/shared/beforewrite.go index b551f3be..7c895777 100644 --- a/internal/shared/beforewrite.go +++ b/internal/shared/beforewrite.go @@ -43,6 +43,14 @@ type beforeWriteWriter struct { mu sync.Mutex hooks []func() committed bool + + // writeFailed records that writing the body returned an error. By then + // the connection is broken (the client went away, or a write deadline + // fired), and the usual next step is an error handler trying to send a + // 500. That WriteHeader has nowhere to go, so it is dropped instead of + // reaching net/http, which would log it as a superfluous WriteHeader and + // point at this file. + writeFailed bool } // WrapBeforeWrite returns w as a BeforeWriter, wrapping it if needed. @@ -143,16 +151,35 @@ func (w *beforeWriteWriter) discard() { func (w *beforeWriteWriter) WriteHeader(code int) { w.commit() - // Deliberately not guarded against a second call. net/http already logs a - // superfluous WriteHeader, and swallowing it here would hide a handler bug - // that is visible without this wrapper in the chain. + + w.mu.Lock() + failed := w.writeFailed + w.mu.Unlock() + + if failed { + return + } + // Otherwise deliberately not guarded against a second call. net/http + // already logs a superfluous WriteHeader, and swallowing it here would + // hide a handler bug that is visible without this wrapper in the chain. w.ResponseWriter.WriteHeader(code) } func (w *beforeWriteWriter) Write(b []byte) (int, error) { w.commit() - return w.ResponseWriter.Write(b) + n, err := w.ResponseWriter.Write(b) + if err != nil { + w.markWriteFailed() + } + + return n, err +} + +func (w *beforeWriteWriter) markWriteFailed() { + w.mu.Lock() + w.writeFailed = true + w.mu.Unlock() } // Flush implements http.Flusher. @@ -193,15 +220,27 @@ func (w *beforeWriteWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { // the wrapper. Commits first, since the copy is a write. func (w *beforeWriteWriter) ReadFrom(src io.Reader) (int64, error) { rf, ok := w.ResponseWriter.(io.ReaderFrom) - if !ok { - w.commit() + w.commit() + + var ( + n int64 + err error + ) - return io.Copy(w.ResponseWriter, src) + if ok { + n, err = rf.ReadFrom(src) + } else { + n, err = io.Copy(w.ResponseWriter, src) } - w.commit() + // A ReadFrom error can come from src as well as from the connection; + // only the connection side means the response is unwritable, but both + // end the response, so a following WriteHeader is no use either way. + if err != nil { + w.markWriteFailed() + } - return rf.ReadFrom(src) + return n, err } // Push implements http.Pusher. diff --git a/internal/shared/beforewrite_failed_write_test.go b/internal/shared/beforewrite_failed_write_test.go new file mode 100644 index 00000000..655051fd --- /dev/null +++ b/internal/shared/beforewrite_failed_write_test.go @@ -0,0 +1,56 @@ +package shared + +import ( + "errors" + "net/http" + "net/http/httptest" + "testing" +) + +// brokenConn fails every body write the way a connection does once the +// client is gone or a write deadline fired, and records WriteHeader calls. +type brokenConn struct { + *httptest.ResponseRecorder + + headers int +} + +func (b *brokenConn) WriteHeader(code int) { + b.headers++ + b.ResponseRecorder.WriteHeader(code) +} + +func (b *brokenConn) Write([]byte) (int, error) { + return 0, errors.New("write: broken pipe") +} + +// After a failed write an error handler typically sends a 500. That reached +// net/http as a superfluous WriteHeader and was logged against this wrapper. +func TestBeforeWrite_DropsWriteHeaderAfterFailedWrite(t *testing.T) { + conn := &brokenConn{ResponseRecorder: httptest.NewRecorder()} + w := WrapBeforeWrite(conn) + + if _, err := w.Write([]byte("body")); err == nil { + t.Fatal("expected the write to fail") + } + + w.WriteHeader(http.StatusInternalServerError) + + if conn.headers != 0 { + t.Errorf("WriteHeader reached the broken connection %d times, want 0", conn.headers) + } +} + +// A second WriteHeader with no failed write in between still goes through, so +// net/http keeps reporting the handler bug. +func TestBeforeWrite_KeepsDuplicateWriteHeaderVisible(t *testing.T) { + conn := &brokenConn{ResponseRecorder: httptest.NewRecorder()} + w := WrapBeforeWrite(conn) + + w.WriteHeader(http.StatusOK) + w.WriteHeader(http.StatusInternalServerError) + + if conn.headers != 2 { + t.Errorf("WriteHeader reached the writer %d times, want 2", conn.headers) + } +} From a0e4f9e9ee77697ce816f3262deae76aa7836db9 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:23:12 -0600 Subject: [PATCH 06/15] fix(lifecycle): bound every shutdown step and exit on a second signal An extension whose Stop ignored its context (select{} in the reproduction, a driver Close or a queue drain in practice) blocked Run forever, and the signal channel was read once, so every later SIGINT or SIGTERM was swallowed and only kill -9 ended the process. Stop also reused the context the HTTP drain had already spent, so every extension stop ran with a context that was done before it started. - The HTTP drain keeps ShutdownTimeout. Stop gets a fresh budget of its own, StopTimeout (WithStopTimeout), which defaults to ShutdownTimeout. - Each stop step (hooks, health manager, every extension, the container, the metrics collector) runs in a goroutine and is waited on only until the budget is spent. A step that overruns is abandoned and logged and the following steps still run. A panicking step is logged too. - Stop with a context that has no deadline is bounded by StopTimeout, and Stop with one that is already done still gives the steps StopTimeout instead of failing them all at once. - The final metrics push, span export, profiler stop and log export each get their own 5s budget, so they still run when the stop budget is gone. - A second shutdown signal logs and exits with status 1. The channel has two slots and is released with signal.Stop when Run returns. - Run now stops the app when a BeforeRun hook fails or ListenAndServe fails (an address in use, typically) instead of returning with every extension still running. - AfterRun hooks run on their own goroutine, where a panic killed the process; it is recovered and logged. --- app.go | 16 +- app_impl.go | 182 +++++++++++++----- lifecycle_shutdown_budget_test.go | 306 ++++++++++++++++++++++++++++++ lifecycle_stop.go | 105 ++++++++++ 4 files changed, 563 insertions(+), 46 deletions(-) create mode 100644 lifecycle_shutdown_budget_test.go create mode 100644 lifecycle_stop.go diff --git a/app.go b/app.go index d04c8243..87b627d8 100644 --- a/app.go +++ b/app.go @@ -131,9 +131,17 @@ type AppConfig struct { HTTPWriteTimeout time.Duration // Shutdown - ShutdownTimeout time.Duration // Default: 30s + ShutdownTimeout time.Duration // HTTP drain budget. Default: 30s ShutdownSignals []os.Signal // Default: SIGINT, SIGTERM + // StopTimeout bounds the second half of a graceful shutdown: lifecycle + // hooks, extension stops and the DI container. It is separate from + // ShutdownTimeout, which the HTTP drain spends, so a slow drain cannot + // leave the extensions with no time at all. A step that overruns is + // abandoned and logged instead of blocking shutdown forever. Zero means + // the same value as ShutdownTimeout. + StopTimeout time.Duration + // ObservabilityGuard authorizes access to the detailed observability // endpoints: the per-check detail of /_/health, /_/info and /_/metrics. // Return false to deny. A denied /_/health caller still gets the overall @@ -538,6 +546,12 @@ func WithHTTPWriteTimeout(timeout time.Duration) AppOption { return func(c *AppConfig) { c.HTTPWriteTimeout = timeout } } +// WithStopTimeout sets the budget for stopping hooks, extensions and the DI +// container during shutdown. See AppConfig.StopTimeout. +func WithStopTimeout(timeout time.Duration) AppOption { + return func(c *AppConfig) { c.StopTimeout = timeout } +} + // WithObservabilityGuard restricts the detailed observability endpoints. The // guard runs on every request to /_/health, /_/info and /_/metrics; see // AppConfig.ObservabilityGuard for what a denied caller sees. diff --git a/app_impl.go b/app_impl.go index eccd9332..1a8ceef3 100644 --- a/app_impl.go +++ b/app_impl.go @@ -70,6 +70,10 @@ type app struct { started bool starting bool + // shuttingDown is set as soon as a shutdown begins, so readiness turns + // 503 and load balancers stop sending traffic while requests drain. + shuttingDown atomic.Bool + // devEnvironment reports whether Environment was explicitly set to a // development one. It gates the defaults that trade safety for debugging // convenience: internal error text in 5xx bodies and health check detail. @@ -991,6 +995,14 @@ type startableService interface { } // Stop stops the application. +// +// Hooks, the health manager, the extensions and the DI container share one +// budget: ctx's deadline or StopTimeout, whichever comes first. A step that +// overruns it is abandoned and logged, and the steps after it still run, so +// one stuck Stop cannot keep the process alive. The telemetry flushes at the +// end (metrics push, spans, profiles, logs) each get a small budget of their +// own, since the stop budget may be spent by then and they are what explains +// the shutdown afterwards. func (a *app) Stop(ctx context.Context) error { a.mu.Lock() defer a.mu.Unlock() @@ -999,18 +1011,25 @@ func (a *app) Stop(ctx context.Context) error { return nil } + a.shuttingDown.Store(true) + a.logger.Info("stopping application") - lctx, stopSpan := a.startLifecycleSpan(ctx, "forge.stop") + stopCtx, cancel := a.stopBudget(ctx) + defer cancel() + + lctx, stopSpan := a.startLifecycleSpan(stopCtx, "forge.stop") // Execute before stop hooks - if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseBeforeStop, a); err != nil { + if err := runStep(stopCtx, "before stop hooks", func(ctx context.Context) error { + return a.lifecycleManager.ExecuteHooks(ctx, PhaseBeforeStop, a) + }); err != nil { a.logger.Warn("before stop hooks failed", F("error", err)) } // 1. Stop health manager if healthMgr, ok := a.healthManager.(*healthinternal.ManagerImpl); ok { - if err := healthMgr.Stop(ctx); err != nil { + if err := runStep(stopCtx, "health manager stop", healthMgr.Stop); err != nil { a.logger.Error("failed to stop health manager", F("error", err)) } } @@ -1021,17 +1040,17 @@ func (a *app) Stop(ctx context.Context) error { // 3. Push metrics one last time and stop pushing, while the collector // still holds them: its Stop resets the registry. The drain and the // extension stops are counted. - a.stopMetricsPush(ctx) + a.flush(ctx, a.stopMetricsPush) // 4. Stop DI container (stops all services in reverse order) - if err := a.container.Stop(ctx); err != nil { + if err := runStep(stopCtx, "container stop", a.container.Stop); err != nil { a.logger.Error("failed to stop container", F("error", err)) } // The container stops the metrics collector only when it started it, so // stop whatever Start started here. if svc, ok := a.metrics.(startableService); ok && svc.IsStarted() { - if err := svc.Stop(ctx); err != nil { + if err := runStep(stopCtx, "metrics collector stop", svc.Stop); err != nil { a.logger.Error("failed to stop metrics collector", F("error", err)) } } @@ -1041,29 +1060,43 @@ func (a *app) Stop(ctx context.Context) error { // 5. Flush spans last, so the drain and the extension stops are exported. if a.tracing != nil { - if err := a.tracing.Shutdown(ctx); err != nil { - a.logger.Warn("tracing shutdown did not finish", F("error", err)) - } + a.flush(ctx, func(ctx context.Context) { + if err := runStep(ctx, "tracing shutdown", a.tracing.Shutdown); err != nil { + a.logger.Warn("tracing shutdown did not finish", F("error", err)) + } + }) } // 6. Stop profiling last, so shutdown shows up in the final profiles. - a.stopProfiler(ctx) + a.flush(ctx, a.stopProfiler) a.started = false // Execute after stop hooks - if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseAfterStop, a); err != nil { + if err := runStep(stopCtx, "after stop hooks", func(ctx context.Context) error { + return a.lifecycleManager.ExecuteHooks(ctx, PhaseAfterStop, a) + }); err != nil { a.logger.Warn("after stop hooks failed", F("error", err)) } a.logger.Info("application stopped") // 7. Flush logs and detach last, so every line above is exported. - a.stopLogsExport(ctx) + a.flush(ctx, a.stopLogsExport) return nil } +// flush runs one telemetry flush with a fresh telemetryFlushTimeout budget. +// The flushes themselves stop at their context's deadline, so they need no +// goroutine of their own. +func (a *app) flush(ctx context.Context, fn func(context.Context)) { + fctx, cancel := flushContext(ctx) + defer cancel() + + fn(fctx) +} + // Run starts the HTTP server and blocks until a shutdown signal is received. func (a *app) Run() error { if os.Getenv("FORGE_INTROSPECT") == "1" { @@ -1092,15 +1125,21 @@ func (a *app) Run() error { // Print startup banner a.printStartupBanner() - // Execute before run hooks (before HTTP server starts) + // Execute before run hooks (before HTTP server starts). The app is + // already started, so a failure here has extensions and services to stop. if err := a.lifecycleManager.ExecuteHooks(context.Background(), PhaseBeforeRun, a); err != nil { + a.stopAfterRunFailure() + return fmt.Errorf("before run hooks failed: %w", err) } - // Channel for shutdown signal - shutdown := make(chan os.Signal, 1) + // Channel for shutdown signal. Two slots, so a second signal sent right + // after the first is not dropped while the first is being handled. + shutdown := make(chan os.Signal, 2) signal.Notify(shutdown, a.config.ShutdownSignals...) + defer signal.Stop(shutdown) + // Channel for server errors errChan := make(chan error, 1) @@ -1113,24 +1152,65 @@ func (a *app) Run() error { // Execute after run hooks (after HTTP server starts, non-blocking) // Run in background to not block main loop - go func() { - if err := a.lifecycleManager.ExecuteHooks(context.Background(), PhaseAfterRun, a); err != nil { - a.logger.Warn("after run hooks failed", F("error", err)) - } - }() + go a.runAfterRunHooks() // Wait for shutdown signal or error select { case err := <-errChan: + // Typically the address is in use. Start succeeded, so stop what + // it started instead of returning with extensions still running. + a.stopAfterRunFailure() + return fmt.Errorf("http server error: %w", err) case sig := <-shutdown: a.logger.Info("shutdown signal received", F("signal", sig.String())) } + // A second signal means the operator has given up waiting. Graceful + // shutdown is bounded, but its budgets can still add up to a minute, + // and an ignored Ctrl-C is how people reach for kill -9. + done := make(chan struct{}) + defer close(done) + + go func() { + select { + case sig := <-shutdown: + a.logger.Error("second shutdown signal received, exiting without finishing graceful shutdown", + F("signal", sig.String())) + forceExit(1) + case <-done: + } + }() + // Graceful shutdown return a.gracefulShutdown() } +// runAfterRunHooks runs the after-run hooks. It runs on a goroutine of its +// own, so a panic in a hook would take the process down with no unwinding of +// the app; it is logged instead. +func (a *app) runAfterRunHooks() { + defer func() { + if r := recover(); r != nil { + a.logger.Error("after run hook panicked", F("panic", fmt.Sprint(r))) + } + }() + + if err := a.lifecycleManager.ExecuteHooks(context.Background(), PhaseAfterRun, a); err != nil { + a.logger.Warn("after run hooks failed", F("error", err)) + } +} + +// stopAfterRunFailure stops a started app when Run cannot go on. +func (a *app) stopAfterRunFailure() { + ctx, cancel := context.WithTimeout(context.Background(), a.stopTimeout()) + defer cancel() + + if err := a.Stop(ctx); err != nil { + a.logger.Error("app shutdown error", F("error", err)) + } +} + // defaultHTTPWriteTimeout is the write deadline for a non-streaming response // when AppConfig.HTTPWriteTimeout is left at zero. const defaultHTTPWriteTimeout = 60 * time.Second @@ -1238,11 +1318,22 @@ func liftWriteDeadlineOnStreams(next http.Handler) http.Handler { } // gracefulShutdown performs a graceful shutdown. +// +// The HTTP drain gets ShutdownTimeout and Stop gets a fresh StopTimeout. They +// used to share one context, which the drain could spend entirely, leaving +// Stop to run every extension stop with a context that was already done. func (a *app) gracefulShutdown() error { + // Readiness turns 503 first, so load balancers stop routing here while + // in-flight requests drain. + a.shuttingDown.Store(true) + ctx, cancel := context.WithTimeout(context.Background(), a.config.ShutdownTimeout) defer cancel() - a.logger.Info("starting graceful shutdown", F("timeout", a.config.ShutdownTimeout)) + a.logger.Info("starting graceful shutdown", + F("timeout", a.config.ShutdownTimeout), + F("stop_timeout", a.stopTimeout()), + ) // 1. End open streams, so they don't hold Shutdown for its whole timeout. // Shutdown waits for every active request and an event stream never @@ -1270,8 +1361,12 @@ func (a *app) gracefulShutdown() error { a.logger.Warn("streams still open at the end of the shutdown timeout", F("error", err)) } - // 3. Stop the application (which stops all services) - if err := a.Stop(ctx); err != nil { + // 3. Stop the application (which stops all services), on a budget of its + // own rather than whatever the drain left. + stopCtx, stopCancel := context.WithTimeout(context.Background(), a.stopTimeout()) + defer stopCancel() + + if err := a.Stop(stopCtx); err != nil { a.logger.Error("app shutdown error", F("error", err)) } @@ -1659,18 +1754,27 @@ func (a *app) stopStartedExtensions(ctx context.Context, started []Extension) { return } - ctx, cancel := context.WithTimeout(ctx, a.config.ShutdownTimeout) + ctx, cancel := context.WithTimeout(ctx, a.stopTimeout()) defer cancel() for _, ext := range slices.Backward(started) { a.logger.Info("stopping extension after failed start", F("extension", ext.Name())) + a.stopExtension(ctx, ext) + } +} - if err := a.traceExtension(ctx, "stop", ext, ext.Stop); err != nil { - a.logger.Error("failed to stop extension", - F("extension", ext.Name()), - F("error", err), - ) - } +// stopExtension stops one extension within ctx's budget. An extension whose +// Stop ignores its context is abandoned at the deadline instead of holding +// up the rest of shutdown. +func (a *app) stopExtension(ctx context.Context, ext Extension) { + err := runStep(ctx, "extension "+ext.Name()+" stop", func(ctx context.Context) error { + return a.traceExtension(ctx, "stop", ext, ext.Stop) + }) + if err != nil { + a.logger.Error("failed to stop extension", + F("extension", ext.Name()), + F("error", err), + ) } } @@ -1683,16 +1787,9 @@ func (a *app) stopExtensions(ctx context.Context) { F("error", err), ) - for _, v := range slices.Backward(a.extensions) { - ext := v + for _, ext := range slices.Backward(a.extensions) { a.logger.Info("stopping extension", F("extension", ext.Name())) - - if err := a.traceExtension(ctx, "stop", ext, ext.Stop); err != nil { - a.logger.Error("failed to stop extension", - F("extension", ext.Name()), - F("error", err), - ) - } + a.stopExtension(ctx, ext) } return @@ -1711,12 +1808,7 @@ func (a *app) stopExtensions(ctx context.Context) { F("extension", ext.Name()), ) - if err := a.traceExtension(ctx, "stop", ext, ext.Stop); err != nil { - a.logger.Error("failed to stop extension", - F("extension", ext.Name()), - F("error", err), - ) - } + a.stopExtension(ctx, ext) } } diff --git a/lifecycle_shutdown_budget_test.go b/lifecycle_shutdown_budget_test.go new file mode 100644 index 00000000..ad078f04 --- /dev/null +++ b/lifecycle_shutdown_budget_test.go @@ -0,0 +1,306 @@ +package forge + +import ( + "context" + "errors" + "net" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/xraph/go-utils/log" + + forgelogger "github.com/xraph/forge/internal/logger" +) + +// stuckExtension's Stop ignores its context, as a driver Close or a consumer +// drain often does. +type stuckExtension struct { + *BaseExtension + + stopCalled atomic.Bool +} + +func (s *stuckExtension) Stop(context.Context) error { + s.stopCalled.Store(true) + select {} +} + +// stopRecordingExtension records its Stop. +type stopRecordingExtension struct { + *BaseExtension + + stopped atomic.Bool +} + +func (r *stopRecordingExtension) Stop(context.Context) error { + r.stopped.Store(true) + + return nil +} + +func newRunApp(t *testing.T, exts ...Extension) *app { + t.Helper() + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + t.Setenv("PORT", "") + + cfg := DefaultAppConfig() + cfg.EnableConfigAutoDiscovery = false + cfg.Environment = "test" + cfg.Logger = NewNoopLogger() + cfg.HTTPAddress = "127.0.0.1:0" + cfg.ShutdownTimeout = 300 * time.Millisecond + cfg.StopTimeout = 700 * time.Millisecond + cfg.Extensions = exts + + return New(WithConfig(cfg)).(*app) +} + +// runInBackground starts Run and returns once its signal handler is +// installed, which is before the after-run hooks are started. +func runInBackground(t *testing.T, a *app) <-chan error { + t.Helper() + + running := make(chan struct{}) + + if err := a.RegisterHookFn(PhaseAfterRun, "test-running", func(context.Context, App) error { + close(running) + + return nil + }); err != nil { + t.Fatal(err) + } + + returned := make(chan error, 1) + + go func() { returned <- a.Run() }() + + select { + case <-running: + case err := <-returned: + t.Fatalf("Run returned early: %v", err) + case <-time.After(10 * time.Second): + t.Fatal("Run never got going") + } + + return returned +} + +// An extension whose Stop never returns used to block Run forever. Shutdown +// is now bounded by ShutdownTimeout plus StopTimeout, and the extensions after +// the stuck one are still stopped. +func TestShutdown_StuckExtensionStopIsAbandoned(t *testing.T) { + stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} + other := &stopRecordingExtension{BaseExtension: NewBaseExtension("cache", "1.0.0", "c")} + a := newRunApp(t, other, stuck) + + returned := runInBackground(t, a) + + start := time.Now() + + if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { + t.Fatal(err) + } + + select { + case <-returned: + case <-time.After(5 * time.Second): + t.Fatal("Run still blocked 5s after SIGTERM with ShutdownTimeout=300ms and StopTimeout=700ms") + } + + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Errorf("shutdown took %v, want about ShutdownTimeout+StopTimeout", elapsed) + } + + if !stuck.stopCalled.Load() { + t.Error("the stuck extension's Stop was never called") + } + + if !other.stopped.Load() { + t.Error("an extension stopped after the stuck one was skipped") + } +} + +// A second signal during a slow shutdown exits instead of being swallowed. +func TestShutdown_SecondSignalExits(t *testing.T) { + exited := make(chan int, 1) + + orig := forceExit + forceExit = func(code int) { exited <- code } + + t.Cleanup(func() { forceExit = orig }) + + stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} + a := newRunApp(t, stuck) + a.config.StopTimeout = 5 * time.Second + + returned := runInBackground(t, a) + + if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { + t.Fatal(err) + } + + // Wait until shutdown is inside the stuck Stop. + deadline := time.Now().Add(5 * time.Second) + for !stuck.stopCalled.Load() && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + + if err := syscall.Kill(syscall.Getpid(), syscall.SIGINT); err != nil { + t.Fatal(err) + } + + select { + case code := <-exited: + if code == 0 { + t.Errorf("forced exit code = 0, want non-zero") + } + case <-time.After(3 * time.Second): + t.Fatal("the second signal was swallowed") + } + + // Run still finishes on its own once the stop budget runs out. + select { + case <-returned: + case <-time.After(10 * time.Second): + t.Fatal("Run never returned") + } +} + +// A BeforeRun hook failure used to return from Run with every extension still +// running. +func TestRun_BeforeRunFailureStopsTheApp(t *testing.T) { + ext := &stopRecordingExtension{BaseExtension: NewBaseExtension("cache", "1.0.0", "c")} + a := newRunApp(t, ext) + + if err := a.RegisterHookFn(PhaseBeforeRun, "boom", func(context.Context, App) error { + return errors.New("boom") + }); err != nil { + t.Fatal(err) + } + + if err := a.Run(); err == nil { + t.Fatal("Run should fail when a BeforeRun hook fails") + } + + if !ext.stopped.Load() { + t.Error("the extension was not stopped") + } + + if a.started { + t.Error("the app still counts as started") + } +} + +// A listener that cannot bind used to return from Run with every extension +// still running. +func TestRun_ListenFailureStopsTheApp(t *testing.T) { + busy, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer busy.Close() + + ext := &stopRecordingExtension{BaseExtension: NewBaseExtension("cache", "1.0.0", "c")} + a := newRunApp(t, ext) + a.config.HTTPAddress = busy.Addr().String() + + returned := make(chan error, 1) + + go func() { returned <- a.Run() }() + + select { + case err := <-returned: + if err == nil { + t.Fatal("Run should fail when the address is in use") + } + case <-time.After(10 * time.Second): + t.Fatal("Run did not return after ListenAndServe failed") + } + + if !ext.stopped.Load() { + t.Error("the extension was not stopped") + } +} + +// A panicking after-run hook runs on a goroutine of its own, where a panic +// used to kill the process. +func TestRun_AfterRunHookPanicIsRecovered(t *testing.T) { + logs := forgelogger.NewTestLogger().(*log.TestLogger) + + cfg := DefaultAppConfig() + cfg.EnableConfigAutoDiscovery = false + cfg.Logger = logs + a := New(WithConfig(cfg)).(*app) + + if err := a.RegisterHookFn(PhaseAfterRun, "panics", func(context.Context, App) error { + panic("hook bug") + }); err != nil { + t.Fatal(err) + } + + a.runAfterRunHooks() + + if !logs.AssertHasLog("ERROR", "after run hook panicked") { + t.Error("the panic was not logged") + } +} + +// Stop called with a context an earlier step already spent still gives the +// extensions a real budget, and a context with no deadline is still bounded. +func TestStop_ExpiredOrUnboundedContext(t *testing.T) { + t.Run("expired", func(t *testing.T) { + var sawLive atomic.Bool + + ext := &ctxCheckingExtension{BaseExtension: NewBaseExtension("db", "1.0.0", "d"), live: &sawLive} + a := newRunApp(t, ext) + + if err := a.Start(context.Background()); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _ = a.Stop(ctx) + + if !sawLive.Load() { + t.Error("the extension got an already-cancelled context") + } + }) + + t.Run("unbounded", func(t *testing.T) { + stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} + a := newRunApp(t, stuck) + + if err := a.Start(context.Background()); err != nil { + t.Fatal(err) + } + + done := make(chan struct{}) + + go func() { + _ = a.Stop(context.Background()) + close(done) + }() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Stop(context.Background()) hung on a stuck extension") + } + }) +} + +type ctxCheckingExtension struct { + *BaseExtension + + live *atomic.Bool +} + +func (c *ctxCheckingExtension) Stop(ctx context.Context) error { + c.live.Store(ctx.Err() == nil) + + return nil +} diff --git a/lifecycle_stop.go b/lifecycle_stop.go new file mode 100644 index 00000000..35cd0dca --- /dev/null +++ b/lifecycle_stop.go @@ -0,0 +1,105 @@ +package forge + +import ( + "context" + "fmt" + "os" + "time" +) + +// telemetryFlushTimeout is the budget each telemetry flush gets at shutdown: +// the last metrics push, the span export and the log export. They run after +// the extensions have stopped, when the stop budget may already be spent, and +// they are what explains a slow or failed shutdown afterwards, so each gets a +// small budget of its own instead of whatever is left. +const telemetryFlushTimeout = 5 * time.Second + +// forceExit ends the process when a second shutdown signal arrives. A +// variable so tests can observe the call instead of losing the test binary. +var forceExit = os.Exit + +// errStepAbandoned reports a shutdown step that did not return in time. The +// step keeps running in its goroutine; shutdown just stops waiting for it. +type errStepAbandoned struct { + step string + cause error +} + +func (e *errStepAbandoned) Error() string { + return fmt.Sprintf("%s did not finish before the stop deadline (%v); abandoned", e.step, e.cause) +} + +func (e *errStepAbandoned) Unwrap() error { return e.cause } + +// runStep runs fn with ctx and waits for it only until ctx is done. +// +// Shutdown code is the code least likely to honour its context: a driver's +// Close, a consumer draining its queue, a hook someone wrote years ago. Called +// inline, one of those that blocks takes the whole shutdown with it and the +// process never exits. Run in a goroutine, it can only cost the time the +// budget allows. A panic is returned as an error rather than crashing a +// shutdown that is otherwise going fine. +// +// A ctx that is already done gets fn started anyway, so a step that returns +// promptly still runs, but nothing waits for it. +func runStep(ctx context.Context, step string, fn func(context.Context) error) error { + done := make(chan error, 1) + + go func() { + defer func() { + if r := recover(); r != nil { + done <- fmt.Errorf("%s panicked: %v", step, r) + } + }() + + done <- fn(ctx) + }() + + select { + case err := <-done: + return err + case <-ctx.Done(): + // A step that finished at the same moment the budget ran out still + // counts as finished. + select { + case err := <-done: + return err + default: + } + + return &errStepAbandoned{step: step, cause: context.Cause(ctx)} + } +} + +// stopBudget returns the context the stop steps share. It is bounded by +// StopTimeout even when the caller's has no deadline, so a stuck step cannot +// hold Stop forever. A caller context that is already done (typically one an +// earlier http.Server.Shutdown spent) does not cancel the steps outright: +// they still get StopTimeout, as they did when they ran inline and ignored +// the context. +func (a *app) stopBudget(ctx context.Context) (context.Context, context.CancelFunc) { + if ctx.Err() != nil { + ctx = context.WithoutCancel(ctx) + } + + return context.WithTimeout(ctx, a.stopTimeout()) +} + +// stopTimeout is StopTimeout, defaulting to ShutdownTimeout. +func (a *app) stopTimeout() time.Duration { + if a.config.StopTimeout > 0 { + return a.config.StopTimeout + } + + if a.config.ShutdownTimeout > 0 { + return a.config.ShutdownTimeout + } + + return 30 * time.Second +} + +// flushContext returns a fresh telemetryFlushTimeout budget that keeps ctx's +// values but not its cancellation or deadline. +func flushContext(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithoutCancel(ctx), telemetryFlushTimeout) +} From b5b75c2fb1f03a6ea1351439f268ef321f07c322 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:23:54 -0600 Subject: [PATCH 07/15] fix(health): make readiness report the real result from the start and 503 on shutdown Readiness answered "ready" for the whole HealthGracePeriod (60s by default) whatever the checks said. The extension health checks were registered after the health manager's first round, so the cached report did not include them until the next scheduled round, 30s later. And readiness stayed 200 while the app shut down. - /_/health/ready no longer applies the grace period. A failing readiness probe only takes the instance out of rotation, so there is nothing to protect, and routing traffic to an instance with a dead dependency is exactly what the probe is for. /_/health keeps the grace period, since platforms commonly use it as a liveness probe. - Start runs a check round right after registering the extension checks, so the first report readiness answers from covers them. - Readiness answers 503 "shutting down" as soon as a graceful shutdown or Stop begins. Liveness is unaffected. --- app.go | 8 ++++- app_impl.go | 26 ++++++++++----- health_readiness_test.go | 68 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 health_readiness_test.go diff --git a/app.go b/app.go index 87b627d8..0cddf311 100644 --- a/app.go +++ b/app.go @@ -172,7 +172,13 @@ type AppConfig struct { ExposeInternalErrors *bool // Health - HealthGracePeriod time.Duration // Grace period after startup during which health endpoints always return 200. Default: 60s + // HealthGracePeriod is how long after startup /_/health answers 200 with + // status "starting" whatever the checks say, so a platform that uses it as + // a liveness probe does not kill an app whose dependencies are still + // warming up. Readiness (/_/health/ready) ignores it and reports the real + // result, so traffic is not routed to an instance that cannot serve it. + // Default: 60s + HealthGracePeriod time.Duration // Extensions Extensions []Extension // Extensions to register with the app diff --git a/app_impl.go b/app_impl.go index 1a8ceef3..234d08cc 100644 --- a/app_impl.go +++ b/app_impl.go @@ -929,8 +929,13 @@ func (a *app) Start(ctx context.Context) (err error) { a.registerExtensionHealthChecks() - // Note: Health manager is already started by container.Start() - // No need to start it again here + // The health manager ran its first round when it started, before the + // extension checks above existed, and the next scheduled round is a + // whole interval away. Run one now so readiness answers from a report + // that covers the extensions from the start. + if len(a.extensions) > 0 { + a.healthManager.Check(ctx) + } a.started = true a.startTime = time.Now() @@ -2483,14 +2488,21 @@ func (a *app) handleHealthReady(ctx Context) error { }) } - // During startup grace period, always return ready to prevent - // PaaS platforms from killing the app before health checks stabilize - if time.Since(a.startTime) < a.config.HealthGracePeriod { - return ctx.JSON(http.StatusOK, map[string]string{ - "status": "starting", + // Once shutdown starts the instance stops taking new work, so tell the + // load balancer before the listener closes rather than after. + if a.shuttingDown.Load() { + return ctx.JSON(http.StatusServiceUnavailable, map[string]string{ + "status": "not ready", + "message": "shutting down", }) } + // No startup grace here. A failed readiness probe only takes the + // instance out of rotation, it never restarts it, so there is nothing to + // protect against, and answering "ready" for the first minute whatever + // the checks say routes traffic to an instance that cannot serve it. + // Start runs a full check round, extension checks included, before the + // endpoint is reachable, so there is always a real report to answer from. report, fresh := a.healthReport(ctx.Request().Context()) if !fresh { diff --git a/health_readiness_test.go b/health_readiness_test.go new file mode 100644 index 00000000..6a5be7af --- /dev/null +++ b/health_readiness_test.go @@ -0,0 +1,68 @@ +package forge + +import ( + "context" + "errors" + "net/http" + "testing" + "time" +) + +// Readiness answers 503 as soon as shutdown starts. +func TestReadiness_TurnsUnreadyOnShutdown(t *testing.T) { + a := newRunApp(t) + a.config.HealthGracePeriod = 0 + + if err := a.Start(context.Background()); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = a.Stop(context.Background()) }) + + if w := get(t, a, "/_/health/ready"); w.Code != http.StatusOK { + t.Fatalf("/_/health/ready = %d before shutdown, want 200", w.Code) + } + + a.shuttingDown.Store(true) + + if w := get(t, a, "/_/health/ready"); w.Code != http.StatusServiceUnavailable { + t.Errorf("/_/health/ready = %d during shutdown, want 503", w.Code) + } + + if w := get(t, a, "/_/health/live"); w.Code != http.StatusOK { + t.Errorf("/_/health/live = %d during shutdown, want 200", w.Code) + } +} + +// unhealthyExtension fails its health check. +type unhealthyExtension struct{ *BaseExtension } + +func (u *unhealthyExtension) Health(context.Context) error { return errors.New("down") } + +// Readiness used to answer "ready" for the whole grace period whatever the +// checks said, and the extension checks only reached the cached report on +// the first scheduled round, 30s after start. +func TestReadiness_IgnoresGraceAndSeesExtensionChecksAtOnce(t *testing.T) { + a := newRunApp(t, &unhealthyExtension{NewBaseExtension("db", "1.0.0", "d")}) + a.config.HealthGracePeriod = time.Minute + + if err := a.Start(context.Background()); err != nil { + t.Fatal(err) + } + + t.Cleanup(func() { _ = a.Stop(context.Background()) }) + + report := a.healthManager.LastReport() + if report == nil || report.Services["extension:db"] == nil { + t.Fatal("the cached report after Start does not include the extension check") + } + + if w := get(t, a, "/_/health/ready"); w.Code != http.StatusServiceUnavailable { + t.Errorf("/_/health/ready = %d inside the grace period with a failing extension, want 503", w.Code) + } + + // The liveness-style endpoint keeps its grace period. + if w := get(t, a, "/_/health"); w.Code != http.StatusOK { + t.Errorf("/_/health = %d inside the grace period, want 200", w.Code) + } +} From 2443b981792c0a1651f8838c10c38c138fc6d38a Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:24:35 -0600 Subject: [PATCH 08/15] fix(config): leave the value out of invalid config warnings bindConfig logged the raw value of every config key that failed to convert. A value in the wrong place is often a secret: a bearer token set where a headers map or a number belongs ends up in the log as plain text. The warning now carries the key and the expected type only, which is enough to find the bad value in the config source. --- config_bind.go | 5 +++- config_bind_secret_test.go | 50 ++++++++++++++++++++++++++++++++++++++ config_bind_test.go | 8 +++++- 3 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 config_bind_secret_test.go diff --git a/config_bind.go b/config_bind.go index 02de12fa..2a7e3e54 100644 --- a/config_bind.go +++ b/config_bind.go @@ -28,10 +28,13 @@ func bindConfig(cm ConfigManager, key string, target any, log Logger) (map[strin for _, f := range bindErr.Fields { bad[f.Key] = true + // The value itself is not logged. A value under the wrong key or of + // the wrong shape is often a secret (a token pasted into a headers + // map, a DSN in a numeric field), and the key and expected type are + // enough to find it. if log != nil { log.Warn("config: ignoring invalid value, using the default", F("key", f.Key), - F("value", f.Value), F("expected", f.Type), ) } diff --git a/config_bind_secret_test.go b/config_bind_secret_test.go new file mode 100644 index 00000000..0eaa850d --- /dev/null +++ b/config_bind_secret_test.go @@ -0,0 +1,50 @@ +package forge + +import ( + "fmt" + "strings" + "testing" +) + +// A value that fails to bind is often a secret in the wrong place, such as a +// bearer token where a headers map belongs. The warning used to print it. +func TestBindConfigDoesNotLogInvalidValues(t *testing.T) { + const secret = "sk_live_s3cr3t" + + cm := NewDefaultConfigManager(captureLogger(t), NewNoOpMetrics(), nil) + cm.Set("tracing", map[string]any{ + "headers": "authorization=Bearer " + secret, + "sample_ratio": secret + "_in_wrong_key", + }) + + log := captureLogger(t) + + var cfg TracingConfig + + bad, err := bindConfig(cm, "tracing", &cfg, log) + if err != nil { + t.Fatal(err) + } + + if !bad["tracing.sample_ratio"] { + t.Fatalf("bad = %v, want tracing.sample_ratio reported", bad) + } + + warnings := 0 + + for _, e := range log.GetLogs() { + if e.Message == invalidValueMsg { + warnings++ + } + + for _, f := range e.Fields { + if strings.Contains(fmt.Sprint(f.Value()), secret) { + t.Errorf("log %q field %q carries the invalid value", e.Message, f.Key()) + } + } + } + + if warnings != len(bad) { + t.Errorf("got %d invalid-value warnings for %d bad keys", warnings, len(bad)) + } +} diff --git a/config_bind_test.go b/config_bind_test.go index 25e6dff1..ab5f3977 100644 --- a/config_bind_test.go +++ b/config_bind_test.go @@ -63,12 +63,18 @@ func TestBindConfigWarnsAndReportsInvalidValues(t *testing.T) { t.Fatalf("warnings = %+v", warns) } - for field, want := range map[string]any{"key": "x.max_size", "value": "big", "expected": "int"} { + for field, want := range map[string]any{"key": "x.max_size", "expected": "int"} { if v, _ := warns[0].Field(field); v != want { t.Fatalf("%s = %#v, want %#v", field, v, want) } } + // The value is left out: an invalid value is often a secret in the + // wrong place. + if v, ok := warns[0].Field("value"); ok { + t.Fatalf("warning carries the value %#v", v) + } + // confy's own warning must not fire as well: one warning per key. if n := len(cmLog.GetLogsByLevel("WARN")); n != 0 { t.Fatalf("confy also logged %d warnings", n) From 30c64345df01a3bf75b94e0abe8ac4e16d1c8caf Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:27:37 -0600 Subject: [PATCH 09/15] fix(tracing): stop letting clients force trace sampling The default sampler was ParentBased(TraceIDRatioBased), and the server middleware extracts the incoming traceparent, so a request whose traceparent said "sampled" was always sampled. Any client could have every request it made sampled and exported: 1000 of 1000 in production at a 0.1 ratio, against about 100 without the header. Sampling by the trace ID's ratio alone would not stop it either, because TraceIDRatioBased reads the ID's low bits and a client chooses the ID; sequential IDs all pass. By default a remote parent that says "sampled" is now sampled at the configured ratio, decided by a hash of the trace ID keyed with a random per-process seed. A client cannot pick IDs that pass, and every span of a trace still gets the same decision in this process. A remote "not sampled" is still followed, since it can only lower a client's own share. The trace ID and trace state are the caller's either way, so propagation is unchanged. AppConfig.TrustRemoteSampling (WithTrustRemoteSampling, or tracing.trust_remote_sampling in the forge config) restores following the caller's decision, for services that only internal callers reach. Without it, traces that cross several forge services are sampled again at each one. Explicit OTEL_TRACES_SAMPLER choices other than the default are unchanged. --- app.go | 16 +++++ app_impl.go | 19 ++++-- internal/telemetry/config.go | 10 ++++ internal/telemetry/sampler.go | 63 +++++++++++++++++++- internal/telemetry/sampler_test.go | 73 ++++++++++++++++++++++- tracing_sampling_trust_test.go | 93 ++++++++++++++++++++++++++++++ 6 files changed, 267 insertions(+), 7 deletions(-) create mode 100644 tracing_sampling_trust_test.go diff --git a/app.go b/app.go index 0cddf311..28a78a59 100644 --- a/app.go +++ b/app.go @@ -165,6 +165,15 @@ type AppConfig struct { // default of 1s; negative disables the cache. MetricsScrapeCacheTTL time.Duration + // TrustRemoteSampling makes the default trace sampler follow the sampled + // flag of an incoming traceparent. Off by default: the flag is whatever + // the client sent, so following it let any client have every request it + // made sampled and exported. Off, a request that carries a traceparent + // keeps its trace ID but is sampled at the configured ratio. Turn it on + // for a service only internal callers reach, so their traces stay whole. + // The forge config key tracing.trust_remote_sampling turns it on too. + TrustRemoteSampling bool + // ExposeInternalErrors decides whether 5xx responses carry the internal // error text. Nil means it follows Environment: only an explicitly set // development, dev, local or test environment exposes it. An unset or @@ -583,6 +592,13 @@ func WithMetricsScrapeCacheTTL(ttl time.Duration) AppOption { return func(c *AppConfig) { c.MetricsScrapeCacheTTL = ttl } } +// WithTrustRemoteSampling makes the default trace sampler follow the sampled +// flag of incoming traceparent headers. Use it only for services that +// untrusted clients cannot reach. See AppConfig.TrustRemoteSampling. +func WithTrustRemoteSampling() AppOption { + return func(c *AppConfig) { c.TrustRemoteSampling = true } +} + // WithExposeInternalErrors overrides whether 5xx responses carry the internal // error text, whatever the environment. See AppConfig.ExposeInternalErrors. func WithExposeInternalErrors(expose bool) AppOption { diff --git a/app_impl.go b/app_impl.go index 234d08cc..8128864f 100644 --- a/app_impl.go +++ b/app_impl.go @@ -2792,10 +2792,11 @@ func buildTracing(config AppConfig, cm ConfigManager, log Logger) *telemetry.Pro fromFile := readTracingFile(cm, log) settings := telemetry.Resolve(telemetry.Inputs{ - Code: config.TracingConfig, - File: fromFile, - Environment: config.Environment, - Getenv: os.Getenv, + Code: config.TracingConfig, + File: fromFile, + Environment: config.Environment, + Getenv: os.Getenv, + TrustRemoteSampling: config.TrustRemoteSampling || trustRemoteSamplingFromFile(cm), }) for _, w := range settings.Warnings { @@ -2820,6 +2821,16 @@ func buildTracing(config AppConfig, cm ConfigManager, log Logger) *telemetry.Pro return provider } +// trustRemoteSamplingKey is the forge config key for +// AppConfig.TrustRemoteSampling. +const trustRemoteSamplingKey = "tracing.trust_remote_sampling" + +// trustRemoteSamplingFromFile reports whether the config file turns on +// trusting incoming sampling decisions. +func trustRemoteSamplingFromFile(cm ConfigManager) bool { + return cm != nil && cm.HasKey(trustRemoteSamplingKey) && cm.GetBool(trustRemoteSamplingKey) +} + // readTracingFile returns the tracing block from the config file. A block that // won't bind at all is logged and ignored. A value that won't convert is logged // and left unset, so its default applies. diff --git a/internal/telemetry/config.go b/internal/telemetry/config.go index 5771dfa4..d4931fb0 100644 --- a/internal/telemetry/config.go +++ b/internal/telemetry/config.go @@ -21,6 +21,10 @@ type Inputs struct { File shared.TracingConfig // from the forge config "tracing" key Environment string Getenv func(string) string + + // TrustRemoteSampling is resolved by the caller from its own config and + // copied into Settings unchanged. + TrustRemoteSampling bool } // Settings is the resolved tracing configuration. @@ -49,6 +53,11 @@ type Settings struct { // AllowedQueryKeys turns url.query on, with every value whose key isn't // listed replaced by REDACTED. Empty records no url.query. AllowedQueryKeys []string + + // TrustRemoteSampling makes the default sampler follow an incoming + // traceparent's sampled flag. When false a remote parent is sampled at + // SampleRatio like a root, so a client cannot force sampling. + TrustRemoteSampling bool } var supportedSamplers = map[string]bool{ @@ -81,6 +90,7 @@ func Resolve(in Inputs) Settings { s.RecordRawPath = firstBoolPtr(in.Code.RecordRawPath, in.File.RecordRawPath, false) s.RecordUserAgent = firstBoolPtr(in.Code.RecordUserAgent, in.File.RecordUserAgent, false) s.AllowedQueryKeys = firstSlice(in.Code.AllowedQueryKeys, in.File.AllowedQueryKeys) + s.TrustRemoteSampling = in.TrustRemoteSampling s.SamplerName, s.SampleRatio = resolveSampler(in, getenv, &s.Warnings) diff --git a/internal/telemetry/sampler.go b/internal/telemetry/sampler.go index eb11905c..ca3b6224 100644 --- a/internal/telemetry/sampler.go +++ b/internal/telemetry/sampler.go @@ -1,6 +1,9 @@ package telemetry import ( + "fmt" + "hash/maphash" + "math" "sync/atomic" "go.opentelemetry.io/otel/attribute" @@ -27,10 +30,68 @@ func BuildSampler(s Settings) sdktrace.Sampler { case "parentbased_always_off": return sdktrace.ParentBased(sdktrace.NeverSample()) default: - return sdktrace.ParentBased(sdktrace.TraceIDRatioBased(s.SampleRatio)) + root := sdktrace.TraceIDRatioBased(s.SampleRatio) + if s.TrustRemoteSampling { + return sdktrace.ParentBased(root) + } + + // A remote parent's sampled flag comes from whoever sent the + // request. Following it lets any client force every one of its + // requests to be sampled and exported. So unless the callers are + // trusted, a remote parent that says "sampled" is sampled at the + // configured ratio instead. One that says "not sampled" is still + // followed: a client can only lower its own share that way, and an + // upstream proxy that already sampled keeps its traces whole. The + // trace ID is the parent's either way, so propagation is unaffected. + return sdktrace.ParentBased(root, + sdktrace.WithRemoteParentSampled(NewRemoteRatioSampler(s.SampleRatio)), + ) + } +} + +// remoteRatioSampler samples a fraction of traces chosen by a keyed hash of +// the trace ID. TraceIDRatioBased reads the trace ID's low bits directly, +// which is fine for IDs this process generated but not for one a client +// sent: picking IDs whose low bits are zero would get every request sampled. +// The hash key is random per process, so the client cannot choose IDs that +// pass, while every span of one trace still gets the same decision here. +type remoteRatioSampler struct { + seed maphash.Seed + bound uint64 // sample when hash < bound + all bool // ratio >= 1 + desc string +} + +// NewRemoteRatioSampler returns a sampler that samples ratio of the traces it +// sees, in a way the trace ID's sender cannot steer. +func NewRemoteRatioSampler(ratio float64) sdktrace.Sampler { + s := &remoteRatioSampler{ + seed: maphash.MakeSeed(), + desc: fmt.Sprintf("RemoteRatioSampler{%g}", ratio), + } + + switch { + case ratio >= 1: + s.all = true + case ratio > 0: + s.bound = uint64(ratio * math.MaxUint64) + } + + return s +} + +func (s *remoteRatioSampler) ShouldSample(p sdktrace.SamplingParameters) sdktrace.SamplingResult { + ts := trace.SpanContextFromContext(p.ParentContext).TraceState() + + if s.all || maphash.Bytes(s.seed, p.TraceID[:]) < s.bound { + return sdktrace.SamplingResult{Decision: sdktrace.RecordAndSample, Tracestate: ts} } + + return sdktrace.SamplingResult{Decision: sdktrace.Drop, Tracestate: ts} } +func (s *remoteRatioSampler) Description() string { return s.desc } + // SamplerOff reports whether the settings turn sampling off entirely. func SamplerOff(s Settings) bool { switch s.SamplerName { diff --git a/internal/telemetry/sampler_test.go b/internal/telemetry/sampler_test.go index 01761763..7be44ea0 100644 --- a/internal/telemetry/sampler_test.go +++ b/internal/telemetry/sampler_test.go @@ -43,9 +43,78 @@ func TestDefaultSamplerFollowsParent(t *testing.T) { t.Fatal("an unsampled parent must not be sampled, even at ratio 1.0") } - s = BuildSampler(Settings{SamplerName: defaultSamplerName, SampleRatio: 0}) + s = BuildSampler(Settings{SamplerName: defaultSamplerName, SampleRatio: 0, TrustRemoteSampling: true}) if !sampled(t, s, remoteParent(true)) { - t.Fatal("a sampled parent must be sampled, even at ratio 0") + t.Fatal("with trusted callers a sampled parent must be sampled, even at ratio 0") + } +} + +// By default a remote "sampled" flag is not trusted: the sender is whoever +// made the request, and following the flag let any client have every request +// sampled and exported. +func TestDefaultSamplerDoesNotTrustRemoteSampledFlag(t *testing.T) { + s := BuildSampler(Settings{SamplerName: defaultSamplerName, SampleRatio: 0}) + if sampled(t, s, remoteParent(true)) { + t.Fatal("ratio 0 must drop a remote parent that claims to be sampled") + } + + s = BuildSampler(Settings{SamplerName: defaultSamplerName, SampleRatio: 1.0}) + if !sampled(t, s, remoteParent(true)) { + t.Fatal("ratio 1.0 must still sample a sampled remote parent") + } +} + +// The remote ratio cannot be steered by choosing trace IDs. TraceIDRatioBased +// samples every ID whose low bits are small, so sequential IDs, which is what +// a client forcing sampling would send, were all sampled. +func TestRemoteRatioSamplerIgnoresChosenTraceIDs(t *testing.T) { + s := BuildSampler(Settings{SamplerName: defaultSamplerName, SampleRatio: 0.1}) + + const n = 10000 + + got := 0 + + for i := range n { + var id trace.TraceID + + id[15] = byte(i) + id[14] = byte(i >> 8) + + parent := trace.NewSpanContext(trace.SpanContextConfig{ + TraceID: id, SpanID: trace.SpanID{1}, TraceFlags: trace.FlagsSampled, Remote: true, + }) + + res := s.ShouldSample(sdktrace.SamplingParameters{ + ParentContext: trace.ContextWithRemoteSpanContext(t.Context(), parent), + TraceID: id, + Name: "x", + }) + + if res.Decision == sdktrace.RecordAndSample { + got++ + } + } + + // 10% of 10000 is 1000; the binomial standard deviation is 30. + if got < 850 || got > 1150 { + t.Fatalf("sampled %d of %d remote parents with chosen IDs at ratio 0.1, want about 1000", got, n) + } +} + +// One trace gets one decision, so a trace that is kept is kept whole here. +func TestRemoteRatioSamplerIsConsistentPerTrace(t *testing.T) { + s := NewRemoteRatioSampler(0.5) + + for i := range 200 { + id := trace.TraceID{byte(i), 7, byte(i * 3)} + p := sdktrace.SamplingParameters{TraceID: id, ParentContext: t.Context()} + + first := s.ShouldSample(p).Decision + for range 5 { + if s.ShouldSample(p).Decision != first { + t.Fatalf("trace %v got different decisions", id) + } + } } } diff --git a/tracing_sampling_trust_test.go b/tracing_sampling_trust_test.go new file mode 100644 index 00000000..c6b53ac7 --- /dev/null +++ b/tracing_sampling_trust_test.go @@ -0,0 +1,93 @@ +package forge + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + sdktrace "go.opentelemetry.io/otel/sdk/trace" +) + +type sampledCounter struct{ sampled atomic.Int64 } + +func (c *sampledCounter) OnStart(context.Context, sdktrace.ReadWriteSpan) {} +func (c *sampledCounter) OnEnd(s sdktrace.ReadOnlySpan) { + if s.SpanContext().IsSampled() { + c.sampled.Add(1) + } +} +func (c *sampledCounter) Shutdown(context.Context) error { return nil } +func (c *sampledCounter) ForceFlush(context.Context) error { return nil } + +// countSampled serves n requests that each carry a client-chosen traceparent +// with the sampled flag set, and returns how many server spans were sampled. +func countSampled(t *testing.T, opts ...AppOption) (int64, string) { + t.Helper() + t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "") + t.Setenv("OTEL_TRACES_SAMPLER", "") + + cfg := DefaultAppConfig() + cfg.EnableConfigAutoDiscovery = false + cfg.Logger = NewNoopLogger() + + a := New(append([]AppOption{WithConfig(cfg), WithAppEnvironment("production")}, opts...)...) + + sp := &sampledCounter{} + if err := RegisterSpanProcessor(a, sp); err != nil { + t.Fatal(err) + } + + _ = a.Router().GET("/x", func(c Context) error { return c.String(http.StatusOK, "ok") }) + + const n = 1000 + + var lastTraceparent string + + for i := range n { + r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/x", nil) + r.Header.Set("traceparent", fmt.Sprintf("00-%032x-%016x-01", i+1, i+1)) + + w := httptest.NewRecorder() + a.Router().ServeHTTP(w, r) + + lastTraceparent = w.Header().Get("traceparent") + } + + return sp.sampled.Load(), lastTraceparent +} + +// Any client could force 100% sampling by sending traceparent with the +// sampled flag, and sequential trace IDs defeated a trace-ID ratio too. In +// production (ratio 0.1) a client now gets about a tenth sampled, and the +// trace ID it sent is still the one the server continues. +func TestTracing_ClientCannotForceSampling(t *testing.T) { + sampled, tp := countSampled(t) + + if sampled > 200 { + t.Fatalf("%d of 1000 requests with a client-set sampled flag were sampled at ratio 0.1", sampled) + } + + if want := fmt.Sprintf("00-%032x-", 1000); len(tp) < len(want) || tp[:len(want)] != want { + t.Errorf("response traceparent %q does not continue the client's trace ID", tp) + } +} + +// With trusted callers the incoming decision is followed, as before. +func TestTracing_TrustRemoteSamplingFollowsCaller(t *testing.T) { + if sampled, _ := countSampled(t, WithTrustRemoteSampling()); sampled != 1000 { + t.Fatalf("trusted callers: %d of 1000 sampled, want all", sampled) + } +} + +// The forge config key turns trust on too. +func TestTracing_TrustRemoteSamplingFromConfigFile(t *testing.T) { + cm := NewDefaultConfigManager(NewNoopLogger(), NewNoOpMetrics(), nil) + cm.Set("tracing", map[string]any{"trust_remote_sampling": true}) + + if sampled, _ := countSampled(t, WithAppConfigManager(cm)); sampled != 1000 { + t.Fatalf("tracing.trust_remote_sampling: %d of 1000 sampled, want all", sampled) + } +} From ee19049e82db88c158bbae299fe012d861cc9ea8 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:33:27 -0600 Subject: [PATCH 10/15] fix(resilience): stop the circuit breaker serializing calls and getting stuck half-open Execute held the breaker's mutex while fn ran, so every caller of a breaker ran one at a time, and a caller with a short deadline waited behind a slow call for as long as it took. Half-open never recovered: it compared cumulative stats that were never reset against HalfOpenMaxRequests, so after one trip every probe was rejected, and closing needed MaxRequests results while only HalfOpenMaxRequests were admitted. Metrics were looked up in the registry under the breaker's lock on every call, and the state-change counter was incremented on every call after the first change. - The lock covers admission and result recording only; fn runs unlocked. - Each state keeps a window of its own results, reset on every change; the decisions read the window. GetStats still reports cumulative totals. - Half-open counts its in-flight probes and admits HalfOpenMaxRequests (at least one). It closes once enough probes succeed to meet SuccessThreshold and reopens as soon as too many fail to reach it. - A result from a call admitted before a state change updates the totals but not the new state's window. - A context that is already done returns its error without running fn. - Metric instruments are looked up once (again on UpdateConfig) and written after the lock is released; the state-change counter counts changes. - The state-change log line reports the old state correctly. --- internal/resilience/circuitbreaker.go | 294 +++++++++++++----- .../circuitbreaker_concurrency_test.go | 254 +++++++++++++++ 2 files changed, 467 insertions(+), 81 deletions(-) create mode 100644 internal/resilience/circuitbreaker_concurrency_test.go diff --git a/internal/resilience/circuitbreaker.go b/internal/resilience/circuitbreaker.go index 08989a38..88068a1f 100644 --- a/internal/resilience/circuitbreaker.go +++ b/internal/resilience/circuitbreaker.go @@ -3,6 +3,7 @@ package resilience import ( "context" "fmt" + "math" "sync" "time" @@ -12,14 +13,53 @@ import ( ) // CircuitBreaker provides circuit breaker functionality. +// +// The mutex covers admission and result recording only, never the protected +// call: callers run concurrently, and a slow call cannot hold up a caller whose +// context has already given up. type CircuitBreaker struct { - config CircuitBreakerConfig - state CircuitState - stats CircuitStats - mu sync.RWMutex - logger logger.Logger - metrics shared.Metrics - lastError time.Time + config CircuitBreakerConfig + state CircuitState + stats CircuitStats // cumulative, for GetStats + mu sync.RWMutex + logger logger.Logger + metrics shared.Metrics + + // window counts the results recorded since the last state change, and + // is what the state decisions read. Cumulative stats never reset, so a + // half-open breaker reading them judged its few probes against the whole + // history and never closed again. + window windowCounts + + // generation increments on every state change. A call records into the + // window only if the state has not changed since it was admitted, so a + // slow call from before a trip cannot sway the next state's decision. + generation uint64 + + // halfOpenInFlight counts admitted half-open probes still running. + halfOpenInFlight int + + // openedAt is when the breaker last opened; it may try again once + // RecoveryTimeout has passed. + openedAt time.Time + + // handles holds the metric instruments, looked up once rather than + // through the registry on every call. + handles *cbMetricHandles +} + +// windowCounts counts results within one state. +type windowCounts struct { + total int64 + failures int64 + successes int64 +} + +// cbMetricHandles are a breaker's metric instruments, one per label set. +type cbMetricHandles struct { + requests [3][2]metrics.Counter // [state][result] + duration [3]metrics.Histogram // [state] + stateChanges metrics.Counter } // CircuitBreakerConfig contains circuit breaker configuration. @@ -74,7 +114,7 @@ func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker { config.Logger = logger.NewLogger(logger.LoggingConfig{Level: "info"}) } - return &CircuitBreaker{ + cb := &CircuitBreaker{ config: config, state: CircuitStateClosed, stats: CircuitStats{ @@ -83,147 +123,225 @@ func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker { logger: config.Logger, metrics: config.Metrics, } + cb.handles = cb.buildHandles() + + return cb } // Execute executes a function with circuit breaker protection. +// +// A context that is already done is returned as an error without running fn +// or counting against the breaker. fn itself takes no context, so a call that +// has started runs to completion. func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() (any, error)) (any, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + + ticket, err := cb.admit() + if err != nil { + return nil, err + } + + start := time.Now() + result, err := fn() + duration := time.Since(start) + + changes, handles := cb.record(ticket, err) + + if handles != nil { + handles.requests[ticket.state][resultIndex(err)].Inc() + handles.duration[ticket.state].Observe(duration.Seconds()) + + for range changes { + handles.stateChanges.Inc() + } + } + + return result, err +} + +// admission is what a call needs to record its result. +type admission struct { + state CircuitState + generation uint64 +} + +// admit decides whether a call may run, moving an open breaker to half-open +// once its recovery timeout has passed. +func (cb *CircuitBreaker) admit() (admission, error) { cb.mu.Lock() defer cb.mu.Unlock() - // Check if circuit is open if cb.state == CircuitStateOpen { - if time.Since(cb.lastError) < cb.config.RecoveryTimeout { - return nil, &CircuitBreakerError{ + if time.Since(cb.openedAt) < cb.config.RecoveryTimeout { + return admission{}, &CircuitBreakerError{ State: CircuitStateOpen, Message: "circuit is open", Time: time.Now(), } } - // Try to move to half-open state + cb.setState(CircuitStateHalfOpen) } - // Check if circuit is half-open and we've reached the limit - if cb.state == CircuitStateHalfOpen && cb.stats.TotalRequests >= int64(cb.config.HalfOpenMaxRequests) { - return nil, &CircuitBreakerError{ - State: CircuitStateHalfOpen, - Message: "half-open request limit reached", - Time: time.Now(), + if cb.state == CircuitStateHalfOpen { + if cb.window.total+int64(cb.halfOpenInFlight) >= int64(cb.halfOpenMax()) { + return admission{}, &CircuitBreakerError{ + State: CircuitStateHalfOpen, + Message: "half-open request limit reached", + Time: time.Now(), + } } + + cb.halfOpenInFlight++ } - // Execute the function - start := time.Now() - result, err := fn() - duration := time.Since(start) + return admission{state: cb.state, generation: cb.generation}, nil +} + +// record counts a finished call and applies any state change it causes. It +// returns the number of state changes and the metric handles to record with, +// so the metrics are written after the lock is released. +func (cb *CircuitBreaker) record(t admission, err error) (int, *cbMetricHandles) { + cb.mu.Lock() + defer cb.mu.Unlock() + + now := time.Now() - // Update statistics cb.stats.TotalRequests++ if err != nil { cb.stats.FailedRequests++ - cb.lastError = time.Now() - cb.stats.LastFailure = time.Now() + cb.stats.LastFailure = now } else { cb.stats.SuccessfulRequests++ - cb.stats.LastSuccess = time.Now() + cb.stats.LastSuccess = now } - // Update circuit state based on results - cb.updateState() + before := cb.stats.StateChanges + + if t.generation == cb.generation { + if t.state == CircuitStateHalfOpen { + cb.halfOpenInFlight-- + } - // Record metrics - if cb.config.EnableMetrics && cb.metrics != nil { - cb.recordMetrics(duration, err) + cb.window.total++ + if err != nil { + cb.window.failures++ + } else { + cb.window.successes++ + } + + cb.updateState() } - return result, err + var handles *cbMetricHandles + if cb.config.EnableMetrics { + handles = cb.handles + } + + return int(cb.stats.StateChanges - before), handles } -// setState sets the circuit breaker state. +// setState sets the circuit breaker state and starts a fresh window. func (cb *CircuitBreaker) setState(newState CircuitState) { - if cb.state != newState { - cb.state = newState - cb.stats.StateChanges++ - cb.stats.LastStateChange = time.Now() - - cb.logger.Info("circuit breaker state changed", - logger.String("name", cb.config.Name), - logger.String("old_state", cb.state.String()), - logger.String("new_state", newState.String())) + if cb.state == newState { + return + } + + old := cb.state + + cb.state = newState + cb.generation++ + cb.window = windowCounts{} + cb.halfOpenInFlight = 0 + cb.stats.StateChanges++ + cb.stats.LastStateChange = time.Now() + + if newState == CircuitStateOpen { + cb.openedAt = cb.stats.LastStateChange } + + cb.logger.Info("circuit breaker state changed", + logger.String("name", cb.config.Name), + logger.String("old_state", old.String()), + logger.String("new_state", newState.String())) } -// updateState updates the circuit breaker state based on current statistics. +// updateState updates the circuit breaker state based on the current window. func (cb *CircuitBreaker) updateState() { switch cb.state { case CircuitStateClosed: - // Check if we should open the circuit if cb.shouldOpen() { cb.setState(CircuitStateOpen) } case CircuitStateHalfOpen: - // Check if we should close or open the circuit - if cb.shouldClose() { - cb.setState(CircuitStateClosed) - } else if cb.shouldOpen() { + // The probes decide as soon as the outcome is settled: open once too + // many have failed to reach SuccessThreshold, close once enough have + // succeeded. + limit := int64(cb.halfOpenMax()) + need := int64(math.Ceil(cb.config.SuccessThreshold * float64(limit))) + + switch { + case cb.window.failures > limit-need: cb.setState(CircuitStateOpen) + case cb.window.successes >= need: + cb.setState(CircuitStateClosed) } case CircuitStateOpen: - // Check if we should move to half-open - if cb.shouldHalfOpen() { - cb.setState(CircuitStateHalfOpen) - } + // Results of calls admitted before the trip are not counted (see + // generation), so nothing here. } } -// shouldOpen determines if the circuit should be opened. +// shouldOpen determines if a closed circuit should be opened. func (cb *CircuitBreaker) shouldOpen() bool { - if cb.stats.TotalRequests < int64(cb.config.MaxRequests) { + if cb.window.total < int64(cb.config.MaxRequests) { return false } - failureRate := float64(cb.stats.FailedRequests) / float64(cb.stats.TotalRequests) + failureRate := float64(cb.window.failures) / float64(cb.window.total) return failureRate >= cb.config.FailureThreshold } -// shouldClose determines if the circuit should be closed. -func (cb *CircuitBreaker) shouldClose() bool { - if cb.stats.TotalRequests < int64(cb.config.MaxRequests) { - return false - } - - successRate := float64(cb.stats.SuccessfulRequests) / float64(cb.stats.TotalRequests) - - return successRate >= cb.config.SuccessThreshold +// halfOpenMax is how many probes a half-open breaker admits, at least one. +func (cb *CircuitBreaker) halfOpenMax() int { + return max(cb.config.HalfOpenMaxRequests, 1) } -// shouldHalfOpen determines if the circuit should move to half-open. -func (cb *CircuitBreaker) shouldHalfOpen() bool { - return time.Since(cb.lastError) >= cb.config.RecoveryTimeout -} +// buildHandles looks up the metric instruments once. +func (cb *CircuitBreaker) buildHandles() *cbMetricHandles { + if cb.metrics == nil || !cb.config.EnableMetrics { + return nil + } + + name := metrics.WithLabel("name", cb.config.Name) + h := &cbMetricHandles{ + stateChanges: cb.metrics.Counter("circuit_breaker_state_changes_total", name), + } -// recordMetrics records circuit breaker metrics. -func (cb *CircuitBreaker) recordMetrics(duration time.Duration, err error) { - // Record request metrics - cb.metrics.Counter("circuit_breaker_requests_total", metrics.WithLabel("name", cb.config.Name), metrics.WithLabel("state", cb.state.String()), metrics.WithLabel("result", cb.getResultLabel(err))).Inc() + for _, st := range []CircuitState{CircuitStateClosed, CircuitStateOpen, CircuitStateHalfOpen} { + state := metrics.WithLabel("state", st.String()) - // Record duration metrics - cb.metrics.Histogram("circuit_breaker_request_duration_seconds", metrics.WithLabel("name", cb.config.Name), metrics.WithLabel("state", cb.state.String())).Observe(duration.Seconds()) + for i, res := range []string{"success", "error"} { + h.requests[st][i] = cb.metrics.Counter("circuit_breaker_requests_total", name, state, metrics.WithLabel("result", res)) + } - // Record state change metrics - if cb.stats.StateChanges > 0 { - cb.metrics.Counter("circuit_breaker_state_changes_total", metrics.WithLabel("name", cb.config.Name)).Inc() + h.duration[st] = cb.metrics.Histogram("circuit_breaker_request_duration_seconds", name, state) } + + return h } -// getResultLabel returns the result label for metrics. -func (cb *CircuitBreaker) getResultLabel(err error) string { +// resultIndex maps a call's error to the result label's index in +// cbMetricHandles.requests. +func resultIndex(err error) int { if err != nil { - return "error" + return 1 } - return "success" + return 0 } // GetState returns the current circuit breaker state. @@ -248,6 +366,9 @@ func (cb *CircuitBreaker) Reset() { defer cb.mu.Unlock() cb.state = CircuitStateClosed + cb.generation++ + cb.window = windowCounts{} + cb.halfOpenInFlight = 0 cb.stats = CircuitStats{ LastStateChange: time.Now(), } @@ -278,7 +399,18 @@ func (cb *CircuitBreaker) UpdateConfig(config CircuitBreakerConfig) { cb.mu.Lock() defer cb.mu.Unlock() + if config.Logger == nil { + config.Logger = cb.logger + } + + if config.Metrics == nil { + config.Metrics = cb.metrics + } + cb.config = config + cb.logger = config.Logger + cb.metrics = config.Metrics + cb.handles = cb.buildHandles() } // String methods for enums diff --git a/internal/resilience/circuitbreaker_concurrency_test.go b/internal/resilience/circuitbreaker_concurrency_test.go new file mode 100644 index 00000000..bf6ffaec --- /dev/null +++ b/internal/resilience/circuitbreaker_concurrency_test.go @@ -0,0 +1,254 @@ +package resilience + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/xraph/go-utils/metrics" + + "github.com/xraph/forge/internal/logger" +) + +func newTestBreaker() *CircuitBreaker { + return NewCircuitBreaker(CircuitBreakerConfig{ + Name: "t", + MaxRequests: 10, + MaxFailures: 5, + FailureThreshold: 0.5, + SuccessThreshold: 0.8, + RecoveryTimeout: 50 * time.Millisecond, + HalfOpenMaxRequests: 3, + EnableMetrics: true, + Logger: logger.NewNoopLogger(), + Metrics: metrics.NewMockMetrics(), + }) +} + +// The mutex used to be held across fn, so every caller of a breaker ran one +// at a time. +func TestCircuitBreaker_CallsRunConcurrently(t *testing.T) { + cb := newTestBreaker() + + var ( + wg sync.WaitGroup + running atomic.Int32 + peak atomic.Int32 + ) + + for range 50 { + wg.Go(func() { + _, _ = cb.Execute(context.Background(), func() (any, error) { + n := running.Add(1) + for { + p := peak.Load() + if n <= p || peak.CompareAndSwap(p, n) { + break + } + } + + time.Sleep(20 * time.Millisecond) + running.Add(-1) + + return nil, nil + }) + }) + } + + wg.Wait() + + if peak.Load() < 10 { + t.Fatalf("at most %d of 50 calls ran at once; the breaker serializes callers", peak.Load()) + } +} + +// Half-open judged its probes against stats that were never reset, and +// needed MaxRequests results while admitting only HalfOpenMaxRequests, so a +// breaker that tripped once never closed again. +func TestCircuitBreaker_HalfOpenRecovers(t *testing.T) { + cb := newTestBreaker() + + fail := func() (any, error) { return nil, errors.New("down") } + ok := func() (any, error) { return "ok", nil } + + for range 10 { + _, _ = cb.Execute(context.Background(), fail) + } + + if cb.GetState() != CircuitStateOpen { + t.Fatalf("state after 10 failures = %v, want open", cb.GetState()) + } + + time.Sleep(60 * time.Millisecond) + + for i := range 3 { + if _, err := cb.Execute(context.Background(), ok); err != nil { + t.Fatalf("probe %d rejected: %v", i, err) + } + } + + if cb.GetState() != CircuitStateClosed { + t.Fatalf("state after 3 good probes = %v, want closed", cb.GetState()) + } + + // Cumulative stats keep the history. + if s := cb.GetStats(); s.TotalRequests != 13 || s.FailedRequests != 10 { + t.Errorf("stats = %+v, want 13 total and 10 failed", s) + } +} + +// A failed probe sends the breaker straight back to open. +func TestCircuitBreaker_HalfOpenFailureReopens(t *testing.T) { + cb := newTestBreaker() + + for range 10 { + _, _ = cb.Execute(context.Background(), func() (any, error) { return nil, errors.New("down") }) + } + + time.Sleep(60 * time.Millisecond) + + _, _ = cb.Execute(context.Background(), func() (any, error) { return nil, errors.New("still down") }) + + if cb.GetState() != CircuitStateOpen { + t.Fatalf("state after a failed probe = %v, want open", cb.GetState()) + } + + if _, err := cb.Execute(context.Background(), func() (any, error) { return nil, nil }); err == nil { + t.Fatal("a reopened breaker should reject until the recovery timeout passes again") + } +} + +// Half-open admits HalfOpenMaxRequests probes in flight, not more. +func TestCircuitBreaker_HalfOpenLimitsInFlightProbes(t *testing.T) { + cb := newTestBreaker() + + for range 10 { + _, _ = cb.Execute(context.Background(), func() (any, error) { return nil, errors.New("down") }) + } + + time.Sleep(60 * time.Millisecond) + + release := make(chan struct{}) + + var ( + wg sync.WaitGroup + admitted atomic.Int32 + rejected atomic.Int32 + ) + + for range 10 { + wg.Go(func() { + _, err := cb.Execute(context.Background(), func() (any, error) { + admitted.Add(1) + <-release + + return nil, nil + }) + + var cbErr *CircuitBreakerError + if errors.As(err, &cbErr) { + rejected.Add(1) + } + }) + } + + deadline := time.Now().Add(2 * time.Second) + for admitted.Load()+rejected.Load() < 10 && rejected.Load() < 7 && time.Now().Before(deadline) { + time.Sleep(time.Millisecond) + } + + close(release) + wg.Wait() + + if admitted.Load() != 3 || rejected.Load() != 7 { + t.Fatalf("admitted %d, rejected %d; want 3 probes admitted", admitted.Load(), rejected.Load()) + } +} + +// A caller whose context has a deadline used to wait behind a slow call on +// the breaker's mutex for as long as that call took. +func TestCircuitBreaker_ContextIsHonoured(t *testing.T) { + cb := newTestBreaker() + + started := make(chan struct{}) + release := make(chan struct{}) + + go func() { + _, _ = cb.Execute(context.Background(), func() (any, error) { + close(started) + <-release + + return nil, nil + }) + }() + + <-started + defer close(release) + + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + begin := time.Now() + + if _, err := cb.Execute(ctx, func() (any, error) { return nil, nil }); err != nil { + t.Fatalf("an unrelated call failed: %v", err) + } + + if elapsed := time.Since(begin); elapsed > 40*time.Millisecond { + t.Fatalf("an independent call took %v behind a slow one", elapsed) + } + + done, cancelDone := context.WithCancel(context.Background()) + cancelDone() + + ran := false + if _, err := cb.Execute(done, func() (any, error) { ran = true; return nil, nil }); !errors.Is(err, context.Canceled) || ran { + t.Fatalf("a done context should return its error without running fn: err=%v ran=%v", err, ran) + } +} + +// The state-change counter counts changes, not every call made after the +// first change, and instruments are looked up once rather than per call. +func TestCircuitBreaker_MetricsCountChangesAndAreCached(t *testing.T) { + m := metrics.NewMockMetrics() + + stateChanges := metrics.NewMockCounter() + m.CounterFunc = func(name string, _ ...metrics.MetricOption) metrics.Counter { + if name == "circuit_breaker_state_changes_total" { + return stateChanges + } + + return metrics.NewMockCounter() + } + + cb := NewCircuitBreaker(CircuitBreakerConfig{ + Name: "m", MaxRequests: 2, FailureThreshold: 0.5, SuccessThreshold: 1, + RecoveryTimeout: time.Hour, HalfOpenMaxRequests: 1, EnableMetrics: true, + Logger: logger.NewNoopLogger(), Metrics: m, + }) + + lookups := m.CounterCalls + + for range 2 { + _, _ = cb.Execute(context.Background(), func() (any, error) { return nil, errors.New("x") }) + } + + for range 5 { + _, _ = cb.Execute(context.Background(), func() (any, error) { return nil, nil }) + } + + if got := cb.GetStats().StateChanges; got != 1 { + t.Fatalf("StateChanges = %d, want 1", got) + } + + if got := stateChanges.Value(); got != 1 { + t.Errorf("circuit_breaker_state_changes_total = %v, want 1", got) + } + + if m.CounterCalls != lookups { + t.Errorf("Execute looked up %d counters in the registry, want 0", m.CounterCalls-lookups) + } +} From 0b8b4dc1077f327805ee26cd0f400cb137ac2db8 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:34:20 -0600 Subject: [PATCH 11/15] fix(debug): accept only local tools on the forge_debug server The debug server listens on 127.0.0.1, but a browser on the same machine can still reach it. Any web page could open a WebSocket to the debug port, since browsers do not apply CORS to upgrades and the upgrade had no Origin check, and read the snapshot: routes, config keys, services, extensions and health. /state had no Host check, so DNS rebinding could read it through any hostname. The read loop also sized a buffer from the frame length the client sent. Every route now requires a loopback Host (localhost, 127.0.0.1 or ::1, any port) and an Origin that is empty or on a loopback host. The CLI and the editor extension send neither a foreign Host nor an Origin, so they are unaffected. Client frames over 64 KB close the connection, and payloads are discarded as they are read instead of being buffered. Only built with -tags forge_debug. --- debug_server.go | 102 +++++++++++++++++++++++++++++----- debug_server_test.go | 127 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 215 insertions(+), 14 deletions(-) create mode 100644 debug_server_test.go diff --git a/debug_server.go b/debug_server.go index c30183b8..16e62b73 100644 --- a/debug_server.go +++ b/debug_server.go @@ -9,7 +9,9 @@ import ( "io" "net" "net/http" + "net/url" "os" + "strings" "time" "github.com/gobwas/ws" @@ -43,17 +45,9 @@ func initDebugServer(a *app) { stopCh: make(chan struct{}), } - mux := http.NewServeMux() - mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"status":"ok"}`) - }) - mux.HandleFunc("/state", ds.handleState) - mux.HandleFunc("/ws", ds.handleWebSocket) - ds.httpSrv = &http.Server{ Addr: addr, - Handler: mux, + Handler: ds.handler(), ReadTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, } @@ -121,6 +115,81 @@ func initDebugServer(a *app) { ) } +// maxDebugFrame caps a WebSocket frame read from a debug client. The debug +// protocol only sends to clients; what they send is pings and closes, so +// anything larger is not a debug client. +const maxDebugFrame = 64 << 10 + +// handler returns the debug server's routes behind the local-only checks. +func (ds *debugState) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"status":"ok"}`) + }) + mux.HandleFunc("/state", ds.handleState) + mux.HandleFunc("/ws", ds.handleWebSocket) + + return localOnly(mux) +} + +// localOnly rejects requests that did not come from a local tool. +// +// The server listens on 127.0.0.1, but a browser on the same machine can +// still reach it: any page can open a WebSocket to localhost (browsers do +// not apply CORS to upgrades), and DNS rebinding lets a page fetch /state +// through a hostname that resolves to 127.0.0.1. Both carry the page's own +// Origin or Host, so requiring a loopback Host and an empty or loopback +// Origin keeps the snapshot (routes, config, services) away from web pages +// while the CLI and the editor extension, which send neither a foreign +// Host nor an Origin, keep working. +func localOnly(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !isLoopbackHost(r.Host) { + http.Error(w, "forbidden host", http.StatusForbidden) + + return + } + + if origin := r.Header.Get("Origin"); origin != "" && !isLoopbackOrigin(origin) { + http.Error(w, "forbidden origin", http.StatusForbidden) + + return + } + + next.ServeHTTP(w, r) + }) +} + +// isLoopbackHost reports whether a Host header names this machine: +// localhost, 127.0.0.1 or ::1, with or without a port. +func isLoopbackHost(host string) bool { + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + + host = strings.TrimSuffix(strings.TrimPrefix(host, "["), "]") + + if strings.EqualFold(host, "localhost") { + return true + } + + ip := net.ParseIP(host) + + return ip != nil && ip.IsLoopback() +} + +// isLoopbackOrigin reports whether an Origin is an http or https origin on a +// loopback host. +func isLoopbackOrigin(origin string) bool { + u, err := url.Parse(origin) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") { + return false + } + + return isLoopbackHost(u.Host) +} + func (ds *debugState) handleState(w http.ResponseWriter, r *http.Request) { snap := ds.buildSnapshot(r.Context()) msg := DebugMessage{ @@ -158,14 +227,19 @@ func (ds *debugState) handleWebSocket(w http.ResponseWriter, r *http.Request) { if err != nil { break } + // The length is the client's to choose, up to 2^63, so it is never + // used to size an allocation. Payloads are discarded as they are + // read, and a frame over the cap ends the connection. + if hdr.Length > maxDebugFrame { + break + } if hdr.Length > 0 { - payload := make([]byte, hdr.Length) - if _, err := io.ReadFull(conn, payload); err != nil { + if _, err := io.CopyN(io.Discard, conn, hdr.Length); err != nil { break } - if hdr.OpCode == ws.OpPing { - _ = ws.WriteHeader(conn, ws.Header{OpCode: ws.OpPong, Fin: true}) - } + } + if hdr.OpCode == ws.OpPing { + _ = ws.WriteHeader(conn, ws.Header{OpCode: ws.OpPong, Fin: true}) } if hdr.OpCode == ws.OpClose { break diff --git a/debug_server_test.go b/debug_server_test.go new file mode 100644 index 00000000..359dfb7d --- /dev/null +++ b/debug_server_test.go @@ -0,0 +1,127 @@ +//go:build forge_debug + +package forge + +import ( + "context" + "encoding/binary" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +func newDebugTestServer(t *testing.T) *httptest.Server { + t.Helper() + t.Setenv("FORGE_DEBUG_PORT", "") + + cfg := DefaultAppConfig() + cfg.EnableConfigAutoDiscovery = false + cfg.Logger = NewNoopLogger() + + ds := &debugState{a: New(WithConfig(cfg)).(*app), hub: newDebugHub(), stopCh: make(chan struct{})} + + srv := httptest.NewServer(ds.handler()) + t.Cleanup(srv.Close) + + return srv +} + +func wsURL(srv *httptest.Server) string { + return "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws" +} + +// Any web page could open a WebSocket to the debug port (browsers do not +// apply CORS to upgrades) and read the app's routes, config and services. +func TestDebugServer_RejectsForeignOrigin(t *testing.T) { + srv := newDebugTestServer(t) + + d := ws.Dialer{Header: ws.HandshakeHeaderHTTP(http.Header{"Origin": {"https://evil.example"}})} + if conn, _, _, err := d.Dial(context.Background(), wsURL(srv)); err == nil { + conn.Close() + t.Fatal("a cross-origin upgrade was accepted") + } + + for _, origin := range []string{"", "http://localhost:3000", "http://127.0.0.1:9080"} { + h := http.Header{} + if origin != "" { + h.Set("Origin", origin) + } + + d := ws.Dialer{Header: ws.HandshakeHeaderHTTP(h)} + + conn, _, _, err := d.Dial(context.Background(), wsURL(srv)) + if err != nil { + t.Fatalf("origin %q rejected: %v", origin, err) + } + + if _, err := wsutil.ReadServerText(conn); err != nil { + t.Fatalf("origin %q got no snapshot: %v", origin, err) + } + + conn.Close() + } +} + +// DNS rebinding reaches /state through a foreign Host header. +func TestDebugServer_RejectsForeignHost(t *testing.T) { + srv := newDebugTestServer(t) + + for host, want := range map[string]int{ + "attacker-rebind.example:9080": http.StatusForbidden, + "localhost:9080": http.StatusOK, + "127.0.0.1": http.StatusOK, + "[::1]:9080": http.StatusOK, + } { + req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL+"/state", nil) + req.Host = host + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + + resp.Body.Close() + + if resp.StatusCode != want { + t.Errorf("Host %q -> %d, want %d", host, resp.StatusCode, want) + } + } +} + +// A frame header may claim any length; it used to size an allocation. +func TestDebugServer_OversizedFrameClosesConnection(t *testing.T) { + srv := newDebugTestServer(t) + + conn, _, _, err := ws.Dial(context.Background(), wsURL(srv)) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + if _, err := wsutil.ReadServerText(conn); err != nil { + t.Fatal(err) + } + + // A masked binary frame header claiming 1 GiB, with no payload. + hdr := []byte{0x82, 0xff} + hdr = binary.BigEndian.AppendUint64(hdr, 1<<30) + hdr = append(hdr, 1, 2, 3, 4) + + if _, err := conn.Write(hdr); err != nil { + t.Fatal(err) + } + + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + + buf := make([]byte, 1) + if _, err := conn.Read(buf); err == nil { + t.Fatal("the server kept the connection open after an oversized frame") + } else if ne, ok := err.(interface{ Timeout() bool }); ok && ne.Timeout() { + t.Fatal("the server is still waiting for the 1 GiB payload") + } +} From 74881b1aceda6edebfd5d727395167029a97b225 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:35:35 -0600 Subject: [PATCH 12/15] style: satisfy golangci-lint in the ops fixes Rename the abandoned-step error to stepAbandonedError, give the new tests request contexts, canonical header names and the blank lines wsl wants, and spread the debug server's frame loop out the same way. --- app_error_exposure_test.go | 2 +- app_write_deadline_test.go | 9 ++++--- debug_server.go | 4 +++ .../metrics/exporters/scrape_cache_test.go | 9 ++++--- .../circuitbreaker_concurrency_test.go | 25 ++++++++++++------- lifecycle_shutdown_budget_test.go | 2 ++ lifecycle_stop.go | 10 ++++---- metrics_scrape_bench_test.go | 4 +-- tracing_sampling_trust_test.go | 4 +-- 9 files changed, 43 insertions(+), 26 deletions(-) diff --git a/app_error_exposure_test.go b/app_error_exposure_test.go index 1074f736..0b43f187 100644 --- a/app_error_exposure_test.go +++ b/app_error_exposure_test.go @@ -30,7 +30,7 @@ func TestExposeInternalErrors_OnlyExplicitDevelopment(t *testing.T) { {"prod", func() App { return New(WithAppEnvironment("prod")) }, false}, {"staging", func() App { return New(WithAppEnvironment("staging")) }, false}, {"production", func() App { return New(WithAppEnvironment("production")) }, false}, - {"typo", func() App { return New(WithAppEnvironment("developmnet")) }, false}, + {"qa", func() App { return New(WithAppEnvironment("qa")) }, false}, {"development option", func() App { return New(WithAppEnvironment("development")) }, true}, {"Development literal", func() App { return NewApp(AppConfig{Environment: "Development"}) }, true}, {"dev", func() App { return New(WithAppEnvironment("dev")) }, true}, diff --git a/app_write_deadline_test.go b/app_write_deadline_test.go index 733c35dc..46a7b499 100644 --- a/app_write_deadline_test.go +++ b/app_write_deadline_test.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "net/http/httptest" + "strconv" "strings" "sync/atomic" "testing" @@ -65,7 +66,7 @@ func TestWriteDeadline_SlowReaderIsCutOff(t *testing.T) { const clients = 5 for range clients { - conn, err := net.Dial("tcp", addr) + conn, err := (&net.Dialer{}).DialContext(t.Context(), "tcp", addr) if err != nil { t.Fatal(err) } @@ -97,7 +98,7 @@ func TestWriteDeadline_SSEKeepsStreaming(t *testing.T) { _ = a.Router().SSE("/events", func(c Context) error { for i := range 8 { - if err := c.WriteSSE("tick", fmt.Sprint(i)); err != nil { + if err := c.WriteSSE("tick", strconv.Itoa(i)); err != nil { return err } @@ -163,7 +164,9 @@ func TestWriteDeadline_StreamAfterOrdinaryRequestOnSameConnection(t *testing.T) srv := newDeadlineServer(t, a) client := srv.Client() - resp, err := client.Get(srv.URL + "/ping") + pingReq, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, srv.URL+"/ping", nil) + + resp, err := client.Do(pingReq) if err != nil { t.Fatal(err) } diff --git a/debug_server.go b/debug_server.go index 16e62b73..0608aa68 100644 --- a/debug_server.go +++ b/debug_server.go @@ -227,20 +227,24 @@ func (ds *debugState) handleWebSocket(w http.ResponseWriter, r *http.Request) { if err != nil { break } + // The length is the client's to choose, up to 2^63, so it is never // used to size an allocation. Payloads are discarded as they are // read, and a frame over the cap ends the connection. if hdr.Length > maxDebugFrame { break } + if hdr.Length > 0 { if _, err := io.CopyN(io.Discard, conn, hdr.Length); err != nil { break } } + if hdr.OpCode == ws.OpPing { _ = ws.WriteHeader(conn, ws.Header{OpCode: ws.OpPong, Fin: true}) } + if hdr.OpCode == ws.OpClose { break } diff --git a/internal/metrics/exporters/scrape_cache_test.go b/internal/metrics/exporters/scrape_cache_test.go index 6405d838..83c27220 100644 --- a/internal/metrics/exporters/scrape_cache_test.go +++ b/internal/metrics/exporters/scrape_cache_test.go @@ -56,7 +56,7 @@ func TestScrapeCache_ConcurrentScrapesShareOneRender(t *testing.T) { for range 50 { wg.Go(func() { rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/_/metrics", nil)) + h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/_/metrics", nil)) if rec.Code != http.StatusOK || rec.Body.String() != "up 1\n" { t.Errorf("got %d %q", rec.Code, rec.Body.String()) @@ -79,7 +79,7 @@ func TestScrapeCache_ExpiresAndKeysByEncoding(t *testing.T) { c.now = func() time.Time { return now } get := func(encoding string) *httptest.ResponseRecorder { - req := httptest.NewRequest(http.MethodGet, "/_/metrics", nil) + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/_/metrics", nil) if encoding != "" { req.Header.Set("Accept-Encoding", encoding) } @@ -120,6 +120,7 @@ func TestScrapeCache_ExpiresAndKeysByEncoding(t *testing.T) { } now = now.Add(time.Second) + get("") if n := next.renders.Load(); n != 3 { @@ -135,7 +136,7 @@ func TestScrapeCache_UncachedScrapesAreCapped(t *testing.T) { for range ScrapeMaxRequestsInFlight { wg.Go(func() { - h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/_/metrics?name[]=up", nil)) + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/_/metrics?name[]=up", nil)) }) } @@ -145,7 +146,7 @@ func TestScrapeCache_UncachedScrapesAreCapped(t *testing.T) { } rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/_/metrics?name[]=up", nil)) + h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/_/metrics?name[]=up", nil)) if rec.Code != http.StatusServiceUnavailable { t.Errorf("scrape over the cap = %d, want 503", rec.Code) diff --git a/internal/resilience/circuitbreaker_concurrency_test.go b/internal/resilience/circuitbreaker_concurrency_test.go index bf6ffaec..d91cd7c7 100644 --- a/internal/resilience/circuitbreaker_concurrency_test.go +++ b/internal/resilience/circuitbreaker_concurrency_test.go @@ -43,6 +43,7 @@ func TestCircuitBreaker_CallsRunConcurrently(t *testing.T) { wg.Go(func() { _, _ = cb.Execute(context.Background(), func() (any, error) { n := running.Add(1) + for { p := peak.Load() if n <= p || peak.CompareAndSwap(p, n) { @@ -53,7 +54,7 @@ func TestCircuitBreaker_CallsRunConcurrently(t *testing.T) { time.Sleep(20 * time.Millisecond) running.Add(-1) - return nil, nil + return struct{}{}, nil }) }) } @@ -116,7 +117,7 @@ func TestCircuitBreaker_HalfOpenFailureReopens(t *testing.T) { t.Fatalf("state after a failed probe = %v, want open", cb.GetState()) } - if _, err := cb.Execute(context.Background(), func() (any, error) { return nil, nil }); err == nil { + if _, err := cb.Execute(context.Background(), func() (any, error) { return struct{}{}, nil }); err == nil { t.Fatal("a reopened breaker should reject until the recovery timeout passes again") } } @@ -145,11 +146,10 @@ func TestCircuitBreaker_HalfOpenLimitsInFlightProbes(t *testing.T) { admitted.Add(1) <-release - return nil, nil + return struct{}{}, nil }) - var cbErr *CircuitBreakerError - if errors.As(err, &cbErr) { + if _, ok := errors.AsType[*CircuitBreakerError](err); ok { rejected.Add(1) } }) @@ -181,11 +181,12 @@ func TestCircuitBreaker_ContextIsHonoured(t *testing.T) { close(started) <-release - return nil, nil + return struct{}{}, nil }) }() <-started + defer close(release) ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) @@ -193,7 +194,7 @@ func TestCircuitBreaker_ContextIsHonoured(t *testing.T) { begin := time.Now() - if _, err := cb.Execute(ctx, func() (any, error) { return nil, nil }); err != nil { + if _, err := cb.Execute(ctx, func() (any, error) { return struct{}{}, nil }); err != nil { t.Fatalf("an unrelated call failed: %v", err) } @@ -205,7 +206,13 @@ func TestCircuitBreaker_ContextIsHonoured(t *testing.T) { cancelDone() ran := false - if _, err := cb.Execute(done, func() (any, error) { ran = true; return nil, nil }); !errors.Is(err, context.Canceled) || ran { + mark := func() (any, error) { + ran = true + + return struct{}{}, nil + } + + if _, err := cb.Execute(done, mark); !errors.Is(err, context.Canceled) || ran { t.Fatalf("a done context should return its error without running fn: err=%v ran=%v", err, ran) } } @@ -237,7 +244,7 @@ func TestCircuitBreaker_MetricsCountChangesAndAreCached(t *testing.T) { } for range 5 { - _, _ = cb.Execute(context.Background(), func() (any, error) { return nil, nil }) + _, _ = cb.Execute(context.Background(), func() (any, error) { return struct{}{}, nil }) } if got := cb.GetStats().StateChanges; got != 1 { diff --git a/lifecycle_shutdown_budget_test.go b/lifecycle_shutdown_budget_test.go index ad078f04..d720a459 100644 --- a/lifecycle_shutdown_budget_test.go +++ b/lifecycle_shutdown_budget_test.go @@ -24,6 +24,7 @@ type stuckExtension struct { func (s *stuckExtension) Stop(context.Context) error { s.stopCalled.Store(true) + select {} } @@ -282,6 +283,7 @@ func TestStop_ExpiredOrUnboundedContext(t *testing.T) { go func() { _ = a.Stop(context.Background()) + close(done) }() diff --git a/lifecycle_stop.go b/lifecycle_stop.go index 35cd0dca..02f1b247 100644 --- a/lifecycle_stop.go +++ b/lifecycle_stop.go @@ -18,18 +18,18 @@ const telemetryFlushTimeout = 5 * time.Second // variable so tests can observe the call instead of losing the test binary. var forceExit = os.Exit -// errStepAbandoned reports a shutdown step that did not return in time. The +// stepAbandonedError reports a shutdown step that did not return in time. The // step keeps running in its goroutine; shutdown just stops waiting for it. -type errStepAbandoned struct { +type stepAbandonedError struct { step string cause error } -func (e *errStepAbandoned) Error() string { +func (e *stepAbandonedError) Error() string { return fmt.Sprintf("%s did not finish before the stop deadline (%v); abandoned", e.step, e.cause) } -func (e *errStepAbandoned) Unwrap() error { return e.cause } +func (e *stepAbandonedError) Unwrap() error { return e.cause } // runStep runs fn with ctx and waits for it only until ctx is done. // @@ -67,7 +67,7 @@ func runStep(ctx context.Context, step string, fn func(context.Context) error) e default: } - return &errStepAbandoned{step: step, cause: context.Cause(ctx)} + return &stepAbandonedError{step: step, cause: context.Cause(ctx)} } } diff --git a/metrics_scrape_bench_test.go b/metrics_scrape_bench_test.go index 15eb1c5a..d8961534 100644 --- a/metrics_scrape_bench_test.go +++ b/metrics_scrape_bench_test.go @@ -44,11 +44,11 @@ func BenchmarkMetricsScrape(b *testing.B) { for i := range routes { for _, id := range []string{"1", "e", "n"} { - h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, fmt.Sprintf("/r%d/%s", i, id), nil)) + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(b.Context(), http.MethodGet, fmt.Sprintf("/r%d/%s", i, id), nil)) } } - req := httptest.NewRequest(http.MethodGet, "/_/metrics", nil) + req := httptest.NewRequestWithContext(b.Context(), http.MethodGet, "/_/metrics", nil) rr := httptest.NewRecorder() h.ServeHTTP(rr, req) diff --git a/tracing_sampling_trust_test.go b/tracing_sampling_trust_test.go index c6b53ac7..c9cfe297 100644 --- a/tracing_sampling_trust_test.go +++ b/tracing_sampling_trust_test.go @@ -48,12 +48,12 @@ func countSampled(t *testing.T, opts ...AppOption) (int64, string) { for i := range n { r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/x", nil) - r.Header.Set("traceparent", fmt.Sprintf("00-%032x-%016x-01", i+1, i+1)) + r.Header.Set("Traceparent", fmt.Sprintf("00-%032x-%016x-01", i+1, i+1)) w := httptest.NewRecorder() a.Router().ServeHTTP(w, r) - lastTraceparent = w.Header().Get("traceparent") + lastTraceparent = w.Header().Get("Traceparent") } return sp.sampled.Load(), lastTraceparent From 8c49966caae04320dd60e6720beb50fc5dd5ee69 Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Sun, 15 Nov 2026 22:37:42 -0600 Subject: [PATCH 13/15] test(config): match the invalid sample_ratio warning by key The warning no longer carries the value, so the test that looked for "lots" in it now looks for the tracing.sample_ratio key. --- tracing_app_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tracing_app_test.go b/tracing_app_test.go index a9704f77..9b006aaf 100644 --- a/tracing_app_test.go +++ b/tracing_app_test.go @@ -357,7 +357,7 @@ func TestAppWarnsOnInvalidSampleRatio(t *testing.T) { found := false for _, e := range log.GetLogsByLevel("WARN") { - if v, _ := e.Field("value"); e.Message == invalidValueMsg && v == "lots" { + if k, _ := e.Field("key"); e.Message == invalidValueMsg && k == "tracing.sample_ratio" { found = true } } From d3bc3b7cd9dbbc49e6ef3b5f47ea80f3840ee72d Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 17 Nov 2026 18:29:51 -0600 Subject: [PATCH 14/15] test(lifecycle): keep the signal-driven shutdown tests off Windows Two shutdown budget tests deliver SIGTERM and SIGINT to the test process with syscall.Kill, which does not exist on Windows, so the root package failed to compile there and the Windows test job failed. They now live in lifecycle_shutdown_signal_test.go behind a !windows build tag. The other shutdown budget tests still run on every platform. --- lifecycle_shutdown_budget_test.go | 84 -------------------------- lifecycle_shutdown_signal_test.go | 98 +++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 84 deletions(-) create mode 100644 lifecycle_shutdown_signal_test.go diff --git a/lifecycle_shutdown_budget_test.go b/lifecycle_shutdown_budget_test.go index d720a459..4cadebac 100644 --- a/lifecycle_shutdown_budget_test.go +++ b/lifecycle_shutdown_budget_test.go @@ -5,7 +5,6 @@ import ( "errors" "net" "sync/atomic" - "syscall" "testing" "time" @@ -88,89 +87,6 @@ func runInBackground(t *testing.T, a *app) <-chan error { return returned } -// An extension whose Stop never returns used to block Run forever. Shutdown -// is now bounded by ShutdownTimeout plus StopTimeout, and the extensions after -// the stuck one are still stopped. -func TestShutdown_StuckExtensionStopIsAbandoned(t *testing.T) { - stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} - other := &stopRecordingExtension{BaseExtension: NewBaseExtension("cache", "1.0.0", "c")} - a := newRunApp(t, other, stuck) - - returned := runInBackground(t, a) - - start := time.Now() - - if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { - t.Fatal(err) - } - - select { - case <-returned: - case <-time.After(5 * time.Second): - t.Fatal("Run still blocked 5s after SIGTERM with ShutdownTimeout=300ms and StopTimeout=700ms") - } - - if elapsed := time.Since(start); elapsed > 3*time.Second { - t.Errorf("shutdown took %v, want about ShutdownTimeout+StopTimeout", elapsed) - } - - if !stuck.stopCalled.Load() { - t.Error("the stuck extension's Stop was never called") - } - - if !other.stopped.Load() { - t.Error("an extension stopped after the stuck one was skipped") - } -} - -// A second signal during a slow shutdown exits instead of being swallowed. -func TestShutdown_SecondSignalExits(t *testing.T) { - exited := make(chan int, 1) - - orig := forceExit - forceExit = func(code int) { exited <- code } - - t.Cleanup(func() { forceExit = orig }) - - stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} - a := newRunApp(t, stuck) - a.config.StopTimeout = 5 * time.Second - - returned := runInBackground(t, a) - - if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { - t.Fatal(err) - } - - // Wait until shutdown is inside the stuck Stop. - deadline := time.Now().Add(5 * time.Second) - for !stuck.stopCalled.Load() && time.Now().Before(deadline) { - time.Sleep(10 * time.Millisecond) - } - - if err := syscall.Kill(syscall.Getpid(), syscall.SIGINT); err != nil { - t.Fatal(err) - } - - select { - case code := <-exited: - if code == 0 { - t.Errorf("forced exit code = 0, want non-zero") - } - case <-time.After(3 * time.Second): - t.Fatal("the second signal was swallowed") - } - - // Run still finishes on its own once the stop budget runs out. - select { - case <-returned: - case <-time.After(10 * time.Second): - t.Fatal("Run never returned") - } -} - -// A BeforeRun hook failure used to return from Run with every extension still -// running. func TestRun_BeforeRunFailureStopsTheApp(t *testing.T) { ext := &stopRecordingExtension{BaseExtension: NewBaseExtension("cache", "1.0.0", "c")} a := newRunApp(t, ext) diff --git a/lifecycle_shutdown_signal_test.go b/lifecycle_shutdown_signal_test.go new file mode 100644 index 00000000..24891f76 --- /dev/null +++ b/lifecycle_shutdown_signal_test.go @@ -0,0 +1,98 @@ +//go:build !windows + +package forge + +// These tests deliver SIGTERM and SIGINT to the test process with +// syscall.Kill, which Windows does not have. The rest of the shutdown budget +// tests live in lifecycle_shutdown_budget_test.go and run everywhere. + +import ( + "syscall" + "testing" + "time" +) + +// An extension whose Stop never returns used to block Run forever. Shutdown +// is now bounded by ShutdownTimeout plus StopTimeout, and the extensions after +// the stuck one are still stopped. +func TestShutdown_StuckExtensionStopIsAbandoned(t *testing.T) { + stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} + other := &stopRecordingExtension{BaseExtension: NewBaseExtension("cache", "1.0.0", "c")} + a := newRunApp(t, other, stuck) + + returned := runInBackground(t, a) + + start := time.Now() + + if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { + t.Fatal(err) + } + + select { + case <-returned: + case <-time.After(5 * time.Second): + t.Fatal("Run still blocked 5s after SIGTERM with ShutdownTimeout=300ms and StopTimeout=700ms") + } + + if elapsed := time.Since(start); elapsed > 3*time.Second { + t.Errorf("shutdown took %v, want about ShutdownTimeout+StopTimeout", elapsed) + } + + if !stuck.stopCalled.Load() { + t.Error("the stuck extension's Stop was never called") + } + + if !other.stopped.Load() { + t.Error("an extension stopped after the stuck one was skipped") + } +} + +// A second signal during a slow shutdown exits instead of being swallowed. + +func TestShutdown_SecondSignalExits(t *testing.T) { + exited := make(chan int, 1) + + orig := forceExit + forceExit = func(code int) { exited <- code } + + t.Cleanup(func() { forceExit = orig }) + + stuck := &stuckExtension{BaseExtension: NewBaseExtension("queue", "1.0.0", "q")} + a := newRunApp(t, stuck) + a.config.StopTimeout = 5 * time.Second + + returned := runInBackground(t, a) + + if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { + t.Fatal(err) + } + + // Wait until shutdown is inside the stuck Stop. + deadline := time.Now().Add(5 * time.Second) + for !stuck.stopCalled.Load() && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + + if err := syscall.Kill(syscall.Getpid(), syscall.SIGINT); err != nil { + t.Fatal(err) + } + + select { + case code := <-exited: + if code == 0 { + t.Errorf("forced exit code = 0, want non-zero") + } + case <-time.After(3 * time.Second): + t.Fatal("the second signal was swallowed") + } + + // Run still finishes on its own once the stop budget runs out. + select { + case <-returned: + case <-time.After(10 * time.Second): + t.Fatal("Run never returned") + } +} + +// A BeforeRun hook failure used to return from Run with every extension still +// running. From 6e418fd21671347dce2287216a22dd5c3947756f Mon Sep 17 00:00:00 2001 From: Rex Raphael Date: Tue, 17 Nov 2026 19:33:11 -0600 Subject: [PATCH 15/15] test(observability): disable the health grace period so windows sees real checks --- app_observability_guard_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app_observability_guard_test.go b/app_observability_guard_test.go index 18677c5c..fecb99e5 100644 --- a/app_observability_guard_test.go +++ b/app_observability_guard_test.go @@ -8,7 +8,6 @@ import ( "net/http/httptest" "strings" "testing" - "time" "github.com/xraph/go-utils/log" @@ -34,7 +33,7 @@ func newExposureApp(t *testing.T, env string, opts ...AppOption) (App, *log.Test cfg := DefaultAppConfig() cfg.Name = "prodapp" cfg.Environment = env - cfg.HealthGracePeriod = time.Nanosecond + cfg.HealthGracePeriod = 0 // a 1ns period still reads as "starting" on Windows, whose clock can report zero uptime cfg.EnableConfigAutoDiscovery = false cfg.Logger = logs cfg.Extensions = []Extension{&leakyExtension{NewBaseExtension("database", "1.2.3", "db")}}