Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ For full documentation, visit https://docs.coldbrew.cloud
## Index

- [Constants](<#constants>)
- [func AddWorkerRunOptions\(opts ...workers.RunOption\)](<#AddWorkerRunOptions>)
- [func InitializeVTProto\(\)](<#InitializeVTProto>)
- [func OTELMeterProvider\(\) otelmetric.MeterProvider](<#OTELMeterProvider>)
- [func SetOTELGRPCClientOptions\(opts ...otelgrpc.Option\)](<#SetOTELGRPCClientOptions>)
Expand Down Expand Up @@ -121,6 +122,17 @@ For full documentation, visit https://docs.coldbrew.cloud
const SupportPackageIsVersion1 = true
```

<a name="AddWorkerRunOptions"></a>
## func [AddWorkerRunOptions](<https://github.com/go-coldbrew/core/blob/main/workers.go#L20>)

```go
func AddWorkerRunOptions(opts ...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.

<a name="InitializeVTProto"></a>
## func [InitializeVTProto](<https://github.com/go-coldbrew/core/blob/main/initializers.go#L452>)

Expand Down Expand Up @@ -319,7 +331,7 @@ type CB interface {
```

<a name="New"></a>
### func [New](<https://github.com/go-coldbrew/core/blob/main/core.go#L1029>)
### func [New](<https://github.com/go-coldbrew/core/blob/main/core.go#L1030>)

```go
func New(c config.Config) CB
Expand Down
3 changes: 2 additions & 1 deletion core.go
Original file line number Diff line number Diff line change
Expand Up @@ -846,9 +846,10 @@ func (c *cb) Run() error {
if len(allWorkers) > 0 {
workerCtx, workerCancel := context.WithCancel(gctx)
c.workerCancel = workerCancel
runOpts := c.buildWorkerRunOpts()
g.Go(func() error {
// workers.Run returns nil on context cancellation (clean shutdown).
return workers.Run(workerCtx, allWorkers)
return workers.Run(workerCtx, allWorkers, runOpts...)
})
}

Expand Down
34 changes: 34 additions & 0 deletions workers.go
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.
Comment thread
ankurs marked this conversation as resolved.
Outdated
// 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
}
175 changes: 175 additions & 0 deletions workers_test.go
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))
}
}

Comment thread
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)
Comment thread
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)
Comment thread
ankurs marked this conversation as resolved.
Outdated
}
Comment thread
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)
Loading