-
Notifications
You must be signed in to change notification settings - Fork 4
feat: expose worker run options and wire Prometheus metrics by default #87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
9b99708
feat: expose worker run options and wire Prometheus metrics by default
ankurs 231e75a
fix: address review feedback on metrics wiring
ankurs 2aa9b00
test: cover the user-metrics-overrides-default-prometheus contract
ankurs c506e33
test: fail loudly if Run does not exit during cleanup
ankurs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package core | ||
|
|
||
| import "github.com/go-coldbrew/workers" | ||
|
|
||
| // Run-level options applied when core.Run() invokes workers.Run. Mutated | ||
| // during init via AddWorkerRunOptions; not concurrency-safe by design (same | ||
| // contract as the OTEL setters in core.go). | ||
| var workerRunOpts []workers.RunOption | ||
|
|
||
| // AddWorkerRunOptions appends [workers.RunOption] values applied when | ||
| // core.Run() invokes [workers.Run]. Use this to configure framework-wide | ||
| // worker behaviour: metrics, run-level interceptors, default jitter, etc. | ||
| // Must be called during init, before Run(). Not concurrency-safe. | ||
| // | ||
| // By default, core wires a Prometheus metrics implementation using the | ||
| // service's APP_NAME unless DISABLE_PROMETHEUS=true or APP_NAME is empty. | ||
| // Pass [workers.WithMetrics] here to override that default; a later | ||
| // WithMetrics wins because workers.WithMetrics overwrites runConfig.metrics | ||
| // on each apply. | ||
| func AddWorkerRunOptions(opts ...workers.RunOption) { | ||
| workerRunOpts = append(workerRunOpts, opts...) | ||
| } | ||
|
|
||
| // buildWorkerRunOpts assembles the option slice passed to workers.Run. The | ||
| // default Prometheus metrics (when enabled) is prepended so that any | ||
| // user-supplied workers.WithMetrics overrides it. | ||
| func (c *cb) buildWorkerRunOpts() []workers.RunOption { | ||
| opts := make([]workers.RunOption, 0, len(workerRunOpts)+1) | ||
| if !c.config.DisablePrometheus && !c.config.DisablePormetheus && c.config.AppName != "" { //nolint:staticcheck // intentional use of deprecated field for backward compatibility | ||
| opts = append(opts, workers.WithMetrics(workers.NewPrometheusMetrics(c.config.AppName))) | ||
| } | ||
| opts = append(opts, workerRunOpts...) | ||
| return opts | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| package core | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "net/http" | ||
| "sync/atomic" | ||
| "testing" | ||
| "time" | ||
|
|
||
| "github.com/go-coldbrew/core/config" | ||
| "github.com/go-coldbrew/workers" | ||
| "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" | ||
| "google.golang.org/grpc" | ||
| ) | ||
|
|
||
| // resetWorkerRunOpts clears the package global between tests. | ||
| func resetWorkerRunOpts(t *testing.T) { | ||
| t.Helper() | ||
| prev := workerRunOpts | ||
| workerRunOpts = nil | ||
| t.Cleanup(func() { workerRunOpts = prev }) | ||
| } | ||
|
|
||
| // recordingMetrics is a forward-compatible workers.Metrics that counts | ||
| // WorkerStarted invocations. | ||
| type recordingMetrics struct { | ||
| workers.BaseMetrics | ||
| started atomic.Int32 | ||
| } | ||
|
|
||
| func (m *recordingMetrics) WorkerStarted(string) { m.started.Add(1) } | ||
|
|
||
| func TestBuildWorkerRunOpts_DefaultPrometheus_AppNameSet(t *testing.T) { | ||
| resetWorkerRunOpts(t) | ||
| c := &cb{config: config.Config{AppName: "test_buildopts_default"}} | ||
|
|
||
| opts := c.buildWorkerRunOpts() | ||
| if len(opts) != 1 { | ||
| t.Fatalf("expected one default option, got %d", len(opts)) | ||
| } | ||
| } | ||
|
|
||
| func TestBuildWorkerRunOpts_NoDefault_WhenDisablePrometheus(t *testing.T) { | ||
| resetWorkerRunOpts(t) | ||
| c := &cb{config: config.Config{ | ||
| AppName: "test_buildopts_disabled", | ||
| DisablePrometheus: true, | ||
| }} | ||
|
|
||
| opts := c.buildWorkerRunOpts() | ||
| if len(opts) != 0 { | ||
| t.Fatalf("expected no options when DisablePrometheus=true, got %d", len(opts)) | ||
| } | ||
| } | ||
|
|
||
| func TestBuildWorkerRunOpts_NoDefault_WhenDeprecatedDisablePormetheus(t *testing.T) { | ||
| resetWorkerRunOpts(t) | ||
| c := &cb{config: config.Config{ | ||
| AppName: "test_buildopts_deprecated", | ||
| DisablePormetheus: true, //nolint:staticcheck // testing deprecated field | ||
| }} | ||
|
|
||
| opts := c.buildWorkerRunOpts() | ||
| if len(opts) != 0 { | ||
| t.Fatalf("expected no options when DisablePormetheus=true, got %d", len(opts)) | ||
| } | ||
| } | ||
|
|
||
| func TestBuildWorkerRunOpts_NoDefault_WhenEmptyAppName(t *testing.T) { | ||
| resetWorkerRunOpts(t) | ||
| c := &cb{config: config.Config{AppName: ""}} | ||
|
|
||
| opts := c.buildWorkerRunOpts() | ||
| if len(opts) != 0 { | ||
| t.Fatalf("expected no default option when AppName is empty, got %d", len(opts)) | ||
| } | ||
| } | ||
|
|
||
| func TestAddWorkerRunOptions_AppendsAndCombinesWithDefault(t *testing.T) { | ||
| resetWorkerRunOpts(t) | ||
| AddWorkerRunOptions(workers.WithDefaultJitter(0)) | ||
| AddWorkerRunOptions(workers.AddInterceptors(noopMiddleware)) | ||
|
|
||
| c := &cb{config: config.Config{AppName: "test_buildopts_combined"}} | ||
| opts := c.buildWorkerRunOpts() | ||
| // 1 default Prometheus + 2 user options | ||
| if len(opts) != 3 { | ||
| t.Fatalf("expected 3 options (1 default + 2 user), got %d", len(opts)) | ||
| } | ||
| } | ||
|
|
||
|
ankurs marked this conversation as resolved.
|
||
| func TestAddWorkerRunOptions_NoDefault_WithoutAppName(t *testing.T) { | ||
| resetWorkerRunOpts(t) | ||
| AddWorkerRunOptions(workers.WithDefaultJitter(5)) | ||
|
|
||
| c := &cb{config: config.Config{}} | ||
| opts := c.buildWorkerRunOpts() | ||
| if len(opts) != 1 { | ||
| t.Fatalf("expected 1 user option (no default), got %d", len(opts)) | ||
| } | ||
| } | ||
|
|
||
| func noopMiddleware(ctx context.Context, info *workers.WorkerInfo, next workers.CycleFunc) error { | ||
| return next(ctx, info) | ||
| } | ||
|
|
||
| // TestRun_WorkerMetricsWired runs the full core.Run lifecycle with a worker | ||
| // and a recording Metrics implementation injected via AddWorkerRunOptions, | ||
| // and asserts that WorkerStarted fires — proving the option reaches workers.Run. | ||
| func TestRun_WorkerMetricsWired(t *testing.T) { | ||
| if testing.Short() { | ||
| t.Skip("skipping end-to-end Run lifecycle in short mode") | ||
| } | ||
| resetWorkerRunOpts(t) | ||
|
|
||
| rec := &recordingMetrics{} | ||
| AddWorkerRunOptions(workers.WithMetrics(rec)) | ||
|
|
||
| svc := &workerLifecycleService{} | ||
| instance := New(config.Config{ | ||
| GRPCPort: 0, | ||
| HTTPPort: 0, | ||
| ListenHost: "127.0.0.1", | ||
| DisableSignalHandler: true, | ||
| DisableNewRelic: true, | ||
| DisableAutoMaxProcs: true, | ||
| DisablePrometheus: true, // suppress the default; recording metrics wins anyway | ||
| }) | ||
| instance.SetService(svc) | ||
|
|
||
| errCh := make(chan error, 1) | ||
| go func() { errCh <- instance.Run() }() | ||
|
|
||
| deadline := time.Now().Add(5 * time.Second) | ||
| for rec.started.Load() == 0 && time.Now().Before(deadline) { | ||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
| if rec.started.Load() == 0 { | ||
| t.Fatal("recordingMetrics.WorkerStarted was never invoked") | ||
| } | ||
|
|
||
| if err := instance.Stop(2 * time.Second); err != nil { | ||
| t.Fatalf("Stop failed: %v", err) | ||
|
ankurs marked this conversation as resolved.
Outdated
|
||
| } | ||
|
|
||
| err := <-errCh | ||
| if err != nil && !errors.Is(err, http.ErrServerClosed) && !errors.Is(err, grpc.ErrServerStopped) { | ||
| t.Fatalf("unexpected Run error: %v", err) | ||
|
ankurs marked this conversation as resolved.
Outdated
|
||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // workerLifecycleService is a CBService + CBWorkerProvider used by the | ||
| // end-to-end test above. The worker blocks on ctx so it stays alive long | ||
| // enough for WorkerStarted to fire. | ||
| type workerLifecycleService struct{} | ||
|
|
||
| func (s *workerLifecycleService) InitHTTP(_ context.Context, _ *runtime.ServeMux, _ string, _ []grpc.DialOption) error { | ||
| return nil | ||
| } | ||
|
|
||
| func (s *workerLifecycleService) InitGRPC(_ context.Context, _ *grpc.Server) error { return nil } | ||
|
|
||
| func (s *workerLifecycleService) Workers() []*workers.Worker { | ||
| return []*workers.Worker{ | ||
| workers.NewWorker("test-lifecycle-worker").HandlerFunc( | ||
| func(ctx context.Context, _ *workers.WorkerInfo) error { | ||
| <-ctx.Done() | ||
| return ctx.Err() | ||
| }, | ||
| ), | ||
| } | ||
| } | ||
|
|
||
| var _ CBWorkerProvider = (*workerLifecycleService)(nil) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.